Lists
π¨π Technique Card: Lists in Python (practical)
π Whatβs a list?
A list is like a box that holds lots of things, all in one place. You can put numbers, words, or even other lists inside!
my_shopping = ["apples", "milk", "bread"] # a list of three strings
Note
We use []
to create a list in python
π οΈ Make your own list
Try typing this into your program:
favourite_animals = ["fox", "elephant", "dog"]
print(favourite_animals)
π’ Get something out of your list
You can grab one item by its position (starting from 0!):
print(favourite_animals[0]) # This prints: fox
print(favourite_animals[2]) # This prints: dog
β Add something to your list
Use .append()
to add an item to the end of the list:
favourite_animals.append("cat")
print(favourite_animals)
π§Ή Remove something from your list
Use .remove()
to take something out:
favourite_animals.remove("fox")
print(favourite_animals)
π§ͺ Try this mini challenge
Can you make a list of your top 3 favourite things and print out a sentence like:
My favourite fairy is Sky.
Tip
Use an f-string
and list index like this:
top_fairies = ["Sky", "Ruby", "Amber", "Fern", "Heather"]
print(f"My favourite fairy is {top_fairies[0]}.")
π§ Useful for projects like:
- Random band name generator
- Animal guessing games
- Quiz games
π Deep Dive
To learn more about lists in Python please see the following card:
π Linked Cards
- π Technique Card: Getting a Random Choice from a List in Python (practical)
- π Technique Card: Tuples in Python (practical)
- π Technique Card: Dictionaries in Python (practical)