Python Lists šŸŽÆ

beginner
21 min

Python Lists šŸŽÆ

Welcome to our Python Lists tutorial! In this lesson, we'll dive into one of the most essential data structures in Python - Lists. By the end, you'll be able to create, manipulate, and understand Python lists like a pro! šŸš€

What are Lists? šŸ“

A list in Python is a collection of items that can be of different data types. Lists are ordered, changeable, and allow duplicate items.

Here's a simple example of a list:

python
my_list = ['apple', 'banana', 'cherry', 42]

šŸ’” Pro Tip: Lists in Python are denoted by square brackets [].

Accessing List Items šŸ’”

Accessing items in a list is as easy as pie! You can use the index number to access the item. Remember, Python uses zero-based indexing, so the first item has an index of 0.

python
my_list = ['apple', 'banana', 'cherry', 42] print(my_list[0]) # Output: apple print(my_list[2]) # Output: cherry

Modifying List Items šŸ’”

You can modify the items in a list by changing the value at the specified index.

python
my_list = ['apple', 'banana', 'cherry', 42] my_list[2] = 'orange' print(my_list) # Output: ['apple', 'banana', 'orange', 42]

Adding Items to a List šŸ’”

There are several ways to add items to a list:

  1. Using the append() method:
python
my_list = ['apple', 'banana', 'cherry', 42] my_list.append('orange') print(my_list) # Output: ['apple', 'banana', 'cherry', 42, 'orange']
  1. Using the insert() method:
python
my_list = ['apple', 'banana', 'cherry', 42] my_list.insert(1, 'orange') print(my_list) # Output: ['apple', 'orange', 'banana', 'cherry', 42]

Removing Items from a List šŸ’”

You can remove items from a list using the remove() method and the pop() method.

  1. Using the remove() method:
python
my_list = ['apple', 'banana', 'cherry', 'orange', 42] my_list.remove('cherry') print(my_list) # Output: ['apple', 'banana', 'orange', 42]
  1. Using the pop() method:
python
my_list = ['apple', 'banana', 'cherry', 'orange', 42] my_list.pop(2) # Remove the item at index 2 print(my_list) # Output: ['apple', 'banana', 'orange', 42]

List Length šŸ“

To find the length of a list, you can use the len() function.

python
my_list = ['apple', 'banana', 'cherry', 'orange', 42] print(len(my_list)) # Output: 5

List Comprehensions šŸ’”

List comprehensions are a concise way to create lists in Python. They make it easier to create complex lists in fewer lines of code.

python
numbers = [i for i in range(10)] print(numbers) # Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Quick Quiz
Question 1 of 1

What is the output of the following code?

By the end of this lesson, you should have a solid understanding of Python lists. You'll be able to create, modify, and manipulate lists with confidence! šŸ’Ŗ

Stay tuned for our next lesson where we'll dive deeper into Python's list methods. Happy coding! šŸš€šŸ’»