Why lists?
Storing your favorite song in a variable is easy. You just set a variable equal to the song name:
song = "One Dance"
But what if someone asked for your top ten favorite songs? Top 100? Writing out a separate variable for every song would take forever. Worse, you would have to remember every variable name and which song it holds. song47 is... which one again?
Luckily, Python has a built-in way to store many values in one place, so all your favorite songs can live together. That's what a list is: one container that holds a whole collection of values, in order.
Vocabulary: a list is a data structure. That's the general name for anything a program uses to organize and store data. Lists are one of the most useful data structures in Python.
Creating a list
You create a list with square brackets. This makes an empty list, ready to be filled later:
list_of_songs = []
Or you can put values in from the get-go, separated by commas:
list_of_songs = ["One Dance", "Happy"]
Two rules to remember: values in a list are separated by commas, and the list keeps them in the exact order you wrote them. "One Dance" is first, "Happy" is second, always, until you change it.
Every item has an index
Just like the letters in a string, every item in a list gets an index: a number that tells you its slot in the list. Here's the part that trips everyone up at first: counting starts at 0, not 1. The first item is at index 0, the second at index 1, and so on.
To get a value out of a list, write the list's name followed by the index in square brackets:
scores = [92, 77, 85, 68, 100] list_of_songs = ["One Dance", "Happy"] print(scores[3]) # the FOURTH item print(list_of_songs[1]) # the SECOND item
68 Happy
Bonus trick: negative indexes count from the end. scores[-1] is the last item (100), scores[-2] is the one before it (68). Handy when you don't know how long the list is!
Adding items: append and insert
Lists don't stay frozen. You can add values whenever you want, using two methods:
- append(value) adds a value to the end of the list.
- insert(index, value) squeezes a value into a specific index, pushing everything after it one slot to the right.
Here's the full song-list program. Press Run and follow along:
list_of_songs = ["One Dance", "Happy"] print("Appending song to end of list:") list_of_songs.append("Despacito") print(list_of_songs) print("Inserting song at second index:") list_of_songs.insert(2, "New Slang") print(list_of_songs) print("Accessing the song located at index 1: ", list_of_songs[1])
Appending song to end of list: ['One Dance', 'Happy', 'Despacito'] Inserting song at second index: ['One Dance', 'Happy', 'New Slang', 'Despacito'] Accessing the song located at index 1: Happy
Look closely: insert(2, "New Slang") put the new song at index 2, so "Despacito" slid from index 2 to index 3. Nothing gets overwritten, everything after just shifts over.
Practice: favorite websites
List of Websites
FeedBuzz is an online company that creates surveys. They want to collect information on the best websites that people can't live without. To help them get started:
- Create a variable list_of_websites that stores an empty list.
- Add 4 websites you can't live without.
- From those 4, print the single most important one by indexing into the list to pull out its name.
# Create an empty list called list_of_websites list_of_websites = [] # Add your four favorite/most used sites list_of_websites.append("codehs.com") list_of_websites.append("wikipedia.org") list_of_websites.append("youtube.com") list_of_websites.append("nasa.gov") # Print the one website you can't live without print(list_of_websites[0])
codehs.com
You could also build the list all at once with list_of_websites = ["codehs.com", ...]. Both are correct. And if your favorite is the third one you added, print list_of_websites[2].
Changing and removing items
List items can also be changed or removed. To change an item, point at its index and set it equal to something new, just like assigning a variable:
list_of_songs = ["One Dance", "Happy", "New Slang", "Despacito"] list_of_songs[2] = "Float On" print(list_of_songs)
['One Dance', 'Happy', 'Float On', 'Despacito']
To remove an item completely, you have two options:
- remove(value) deletes a specific value from the list.
- pop(index) deletes whatever is at a specific index.
list_of_songs = ["One Dance", "Happy", "Float On", "Despacito"] list_of_songs.remove("Happy") # removes the VALUE "Happy" list_of_songs.pop(1) # removes whatever is at INDEX 1 print(list_of_songs)
['One Dance', 'Despacito']
Follow it step by step: remove("Happy") leaves ['One Dance', 'Float On', 'Despacito']. Then "Float On" is sitting at index 1, so pop(1) takes it out.
Two gotchas: if you call pop() with no index, it removes the last item. And remove() only deletes the first matching value it finds, not every copy of it.
List playground
Time to drive a list yourself. Below is a real list, my_foods, drawn as a shelf of numbered slots. Append, pop, and change items, and watch the indexes renumber themselves. Every button shows you the exact Python it just ran.
List playground
my_foods : listAppend an item
Adds to the end of the list.
Remove the last item
pop() with no index takes the last one.
Change an item
my_foods[index] = "new value"
Tip: click any slot above to look it up instantly. Negative indexes work too. Try an index that's too big and see what Python says.
Practice: too many Jojos
Fix the Flight List
An airline accidentally added the same passenger to their flight a few too many times. Alter the list so only one "Jojo" remains, and use three different methods to change or remove the extra names.
flight_list = ["Jojo", "Riley", "Steven", "Jojo", "Kiley", "Jojo", "Eva", "Jojo"] # Use three different methods so that only one Jojo remains # print the flight_list
flight_list = ["Jojo", "Riley", "Steven", "Jojo", "Kiley", "Jojo", "Eva", "Jojo"] # Method 1: remove() deletes the FIRST "Jojo" it finds (index 0) flight_list.remove("Jojo") # now: ['Riley', 'Steven', 'Jojo', 'Kiley', 'Jojo', 'Eva', 'Jojo'] # Method 2: pop() deletes the "Jojo" sitting at index 2 flight_list.pop(2) # now: ['Riley', 'Steven', 'Kiley', 'Jojo', 'Eva', 'Jojo'] # Method 3: change the "Jojo" at index 3 into a new passenger flight_list[3] = "Marcus" print(flight_list)
['Riley', 'Steven', 'Kiley', 'Marcus', 'Eva', 'Jojo']
The tricky part: every time you remove someone, the indexes shift. That's why the solution tracks where each remaining "Jojo" landed after each step before picking the next index.
len(), loops, and more
Beyond the methods you've already used, Python gives you plenty of other handy tools for lists:
- len(my_list) returns how many items are in the list.
- my_list.index(value) returns the index of the first item with that value.
- my_list.reverse() flips the order of the list.
- my_list.sort() puts the list in order (alphabetical or smallest-to-largest).
And here's the superpower that makes lists so useful: a for loop can visit every item, no matter how many there are. This program works the same whether the list has 4 songs or 4,000:
list_of_songs = ["One Dance", "Happy", "New Slang", "Despacito"] print("My playlist has", len(list_of_songs), "songs:") for song in list_of_songs: print("Now playing:", song)
My playlist has 4 songs: Now playing: One Dance Now playing: Happy Now playing: New Slang Now playing: Despacito
Think you've got the hang of lists? See how you do on this quiz.
A list example
Lists store many values in one variable. This program builds a list of scores and does a few common operations.
Quick quiz
1. What does print(pets[1]) print if pets = ["cat", "dog", "fish"]?
2. Which line adds "snacks" to the END of a list called backpack?
3. What does this program print?
colors = ["red", "blue", "green"] colors.pop() print(len(colors))
Keep learning Python
Lists hold a whole collection in one variable. Next, stack lists inside lists to build grids, or learn dictionaries, which label each value with a key instead of an index.