Lesson 5 - Lists
Lists in Python
List is a collection that can store multiple values in a single variable.
# Example of a list
fruits = ["apple", "banana"]
print(fruits)
fruits = ["apple", "banana"]
print(fruits)
# Access by index
numbers = [10, 20, 30]
print(numbers[0])
numbers = [10, 20, 30]
print(numbers[0])
# Change an item
colors = ["red", "blue"]
colors[1] = "green"
print(colors)
colors = ["red", "blue"]
colors[1] = "green"
print(colors)
You can add, remove or change items inside a list.
💡 sort() puts the list items in order (alphabetical for words, smallest to biggest for numbers).
# Add an item
animals = ["cat", "dog"]
animals.append("elephant")
print(animals)
animals = ["cat", "dog"]
animals.append("elephant")
print(animals)
# Remove an item
pets = ["dog", "cat"]
pets.remove("cat")
print(pets)
pets = ["dog", "cat"]
pets.remove("cat")
print(pets)
# Sort list
letters = ["a", "c", "b"]
letters.sort()
print(letters)
letters = ["a", "c", "b"]
letters.sort()
print(letters)
Looping and slicing help you work with multiple list items at once.
# Loop through a list
friends = ["Lina", "Max"]
for f in friends:
print("Hello", f)
friends = ["Lina", "Max"]
for f in friends:
print("Hello", f)
# Slice a list
numbers = [1, 2, 3, 4, 5]
print(numbers[1:4])
numbers = [1, 2, 3, 4, 5]
print(numbers[1:4])
# Combine lists
a = [1, 2]
b = [3, 4]
c = a + b
print(c)
a = [1, 2]
b = [3, 4]
c = a + b
print(c)
Make a List
fruits = ["apple", "banana", "cherry"]
print(fruits)
print(fruits)
🎯 Add your own fruit.
Access by Index
numbers = [10, 20, 30]
print(numbers[0])
print(numbers[2])
print(numbers[0])
print(numbers[2])
💡 Remember: counting starts at 0.
Change an Item
colors = ["red", "blue", "green"]
colors[1] = "yellow"
print(colors)
colors[1] = "yellow"
print(colors)
🎯 Try changing another color.
Add to a List
animals = ["cat", "dog"]
animals.append("elephant")
print(animals)
animals.append("elephant")
print(animals)
💡 Append adds to the end.
Remove from a List
pets = ["dog", "cat", "hamster"]
pets.remove("cat")
print(pets)
pets.remove("cat")
print(pets)
🎯 Try removing something else.
List Length
letters = ["a", "b", "c", "d"]
print(len(letters))
print(len(letters))
💡 How many items are there?
Slicing a List
numbers = [1, 2, 3, 4, 5]
print(numbers[1:4])
print(numbers[1:4])
🎯 Which numbers do you see?
Loop Through a List
friends = ["Lina", "Max", "Zara"]
for f in friends:
print("Hello", f)
for f in friends:
print("Hello", f)
💡 Add your name and run again.
Sort a List
scores = [40, 10, 30, 20]
scores.sort()
print(scores)
scores.sort()
print(scores)
🎯 Try with words instead of numbers.
Mix Lists
a = [1, 2]
b = [3, 4]
c = a + b
print(c)
b = [3, 4]
c = a + b
print(c)
💡 What happens if you do b + a?