What You Will Learn
A list stores multiple values in a single variable. Instead of creating ten separate variables for ten names, you create one list.
Creating a List
Use square brackets, with items separated by commas:
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = ["Alice", 25, True, 3.14]
empty = []
print(fruits)
print(len(fruits))
Expected output:
['apple', 'banana', 'cherry']
3
Lists can hold any type of value, including a mix of types.
Accessing Items
Use the index (starting at 0):
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[1]) # banana
print(fruits[-1]) # cherry (last item)
Modifying Items
Lists are mutable — you can change them after creation:
fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"
print(fruits)
Expected output:
['apple', 'blueberry', 'cherry']
Common List Methods
Adding Items
fruits = ["apple", "banana"]
fruits.append("cherry") # add to end
print(fruits)
fruits.insert(1, "blueberry") # insert at index 1
print(fruits)
Expected output:
['apple', 'banana', 'cherry']
['apple', 'blueberry', 'banana', 'cherry']
Removing Items
fruits = ["apple", "banana", "cherry", "banana"]
fruits.remove("banana") # removes first occurrence
print(fruits)
popped = fruits.pop() # removes and returns last item
print(popped)
print(fruits)
Expected output:
['apple', 'cherry', 'banana']
banana
['apple', 'cherry']
Sorting
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort()
print(numbers)
words = ["banana", "apple", "cherry"]
words.sort()
print(words)
Expected output:
[1, 1, 2, 3, 4, 5, 6, 9]
['apple', 'banana', 'cherry']
Looping Over a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
Expected output:
I like apple
I like banana
I like cherry
Checking if an Item Exists
fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
print("We have bananas!")
if "mango" not in fruits:
print("No mangoes.")
Expected output:
We have bananas!
No mangoes.
List Slicing
Like strings, you can slice a list:
numbers = [0, 1, 2, 3, 4, 5]
print(numbers[1:4]) # [1, 2, 3]
print(numbers[:3]) # [0, 1, 2]
print(numbers[3:]) # [3, 4, 5]
What You Learned
- Lists store multiple values in one variable
- Access items with
[index], starting at 0 - Lists are mutable — you can add, remove, and change items
- Common methods:
.append(),.insert(),.remove(),.pop(),.sort() - Use
into check if an item exists
In the next lesson, you will learn about dictionaries — a way to store data as key-value pairs.