π Lists in Python#
Lists are one of the most useful and flexible data structures in Python. They let you store collections of itemsβwhether numbers, strings, or even other lists! Get ready to learn how to create, modify, and use lists like a pro. π₯
What is a List? π§©#
A list is an ordered collection of items enclosed in square brackets [ ]
. You can store multiple values in one list.
fruits = ["apple", "banana", "cherry"]
numbers = [10, 20, 30, 40]
Creating Lists βοΈ#
Lists can contain any type of data and even a mix of types!
mixed_list = [1, "hello", True, 3.14]
empty_list = []
Accessing Items in a List π#
Use indexing to access elements (starting at 0).
print(fruits[^0]) # apple
print(fruits[-1]) # cherry (last item)
Modifying Lists βοΈ#
You can change values, add new items, or remove items.
# Change item
fruits[^1] = "blueberry"
# Add item (append adds to the end)
fruits.append("orange")
# Insert item at specific position
fruits.insert(1, "mango")
# Remove item by value
fruits.remove("apple")
# Remove item by position
del fruits[^2]
List Operations π’#
Operation | Example | Result |
---|---|---|
Concatenate | [^1][^2] + | [^1][^2] |
Repeat | * 3 | `` |
Length | len(fruits) | Number of items in list |
Check membership | "apple" in fruits | True or False |
Looping Through Lists π#
You can use a for
loop to go through each item.
for fruit in fruits:
print(fruit)
Practice Questions with Solutions π#
- Practice: Create a list of your 3 favorite colors and print the first color.
- Solution:
colors = ["red", "green", "blue"]
print(colors)
- Practice: Add the color “yellow” at the end of the list.
- Solution:
colors.append("yellow")
- Practice: Remove the second item from the list.
- Solution:
del colors[^1]
Step-by-Step Mini Project: Shopping List π#
Create a shopping list program that:
- Starts with empty list
- Adds 3 items to the list
- Prints all items to the user
Solution:
shopping_list = []
shopping_list.append("milk")
shopping_list.append("bread")
shopping_list.append("eggs")
print("Your shopping list:")
for item in shopping_list:
print("-", item)
Checklist for This Chapter β #
- Created and accessed lists
- Modified, added, and removed list items
- Used list operations (concatenation, repetition)
- Loop through lists for display
Youβre mastering Python lists! Start collecting and organizing data with ease. Keep practicing by making playlists, scores, or task lists! π
β