…
…
Python Programming Fundamentals · Lesson 23 / 40 · Lists
PreviewIn this lesson you will
list[i] = x, append, insert, remove, and popYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
At Corner Café, a customer first asks for a latte, then two cookies; a few seconds later she changes her mind and puts one cookie back. Ada wants the register to keep the order item by item and to update itself every time an item is added or removed. For that we need a structure that holds many values under one name and can be changed afterward: a list.
So far every variable has held a single value: a price, a product name, a true or false. A cart, however, holds many items, and their number keeps changing. You could try opening a separate variable for each item: item1, item2, item3. But when the customer asks for a fourth item you have to invent a new name, and when someone drops an item you have to track which name is now empty. If you do not know the number of items while writing the program, this way never works.
You have actually met lists twice already. In lesson 10 you looped over a ready-made list in square brackets by writing for item in ["tea", "latte"]:. In lesson 21, split gave you a result in square brackets; that result was also a list. Today we will build a list ourselves, look inside it, and, most importantly, change it. Lists appear in almost every program; the day's sales, the grades of a class, and the lines read from a file are all kept in lists.
At the end of the lesson, the program you write will use two functions, one that adds items to the cart and one that removes items from it, and print this:
OutputCart: ['latte', 'cookie', 'cookie']
Removed? True
Removed? False
Cart: ['latte', 'cookie']
Items: 2 · First: latte · Last: cookieIn this lesson you will be able to:
A list is a structure that keeps many values in order under a single name. It is written with square brackets, and the elements are separated by commas: cart = ["latte", "cookie", "tea"]. A list with nothing in it is the empty list, written []; elements are added later. A list can hold values of any type: strings, numbers, True or False. Still, in practice we put things of the same type in one list: a list of product names, a list of prices.
The good news: all the access rules you learned for strings in lesson 20 work the same way on lists. The index starts at 0: cart[0] is the first element, cart[1] the second. A negative index counts from the end: cart[-1] is the last element. The slice cart[a:b] takes a and leaves out b. len(cart) gives the number of elements, and "water" in cart tells you whether a value is in the list. The only difference is that you now work with elements instead of characters: cart[0] gives you not a letter but a whole item. A slice also gives you a new list.
Example 1 (case): Looking at the cart
cart = ["latte", "cookie", "tea"] print(cart[0], cart[-1]) print(cart[1:]) print(len(cart), "water" in cart)
Outputlatte tea
['cookie', 'tea']
3 FalseThe first line printed the first and the last item. The slice on the second line returned the items from position 1 to the end as a new list; Python shows a list with square brackets and quotes. The third line said there are 3 items in the cart and that water is not one of them. Note one detail: in looks for an element in a list; it does not look for a piece, as it does in a string. "lat" in "latte" is true, but "lat" in ["latte"] is false, because there is no element "lat" in the list.
What if you ask for a position that is not in the cart? In a cart of 3 items the positions are 0, 1, and 2. When you ask for cart[3], Python gives this error:
cart = ["latte", "cookie", "tea"] print(cart[3])
OutputIndexError: list index out of rangeThe message is the list version of the error you saw with strings in lesson 20: "list index out of range". The last valid index is always len(cart) - 1. Now try counting from 0 on a list too.
What does this code print?
cart = ["latte", "tea", "water"] print(cart[1], len(cart))
Thinking that the first element of a list is cart[1] is the most common misunderstanding; another is thinking that a slice, like a single index, raises an error when it goes past the end. As with strings, if a slice runs past the end of the list it returns what is there; a single index asks for a position that does not exist, so it raises an error. Below, match seven expressions on the same price list with their results. Two results are extra.
For prices = [4.25, 2.00, 1.25, 0.75], what does each expression give?
For each row, pick its match from the list, then check.
prices[0]prices[-1]prices[1:3]prices[2:10]len(prices)2.0 in pricesprices[4]In lesson 20 we saw that we cannot change one letter of a string in place: code[0] = "C" raised an error and we had to build a new string. A list differs from a string here: an element of a list changes in place. The syntax is reading by index turned into an assignment: prices[1] = 2.25. The left side is "position 1 of the list", and the right side is the new value that goes to that position. The old value goes away, and the rest of the list stays as it was.
Example 2 (case): Updating a price
prices = [4.25, 2.00, 1.25]
prices[1] = 2.25
print(prices)Output[4.25, 2.25, 1.25]When you try the same thing on a string, Python objects:
item = "latte" item[0] = "L"
OutputTypeError: 'str' object does not support item assignmentThe message says "the str type does not support item assignment". On a list, the same syntax worked without trouble. This is why we keep things that change during the day, such as a cart, a stock count, or a waiting queue, as lists: instead of building a new value for each change, we update the same list. There is one limit: an assignment changes only a position that already exists. If you write prices[3] = 0.75 on a list of 3 elements, you get IndexError: list assignment index out of range; an assignment does not make the list longer. We will see how to add new elements to a list in a moment.
Now try this yourself. Example 2 is ready in the cell. First press Run, then do the task in the comment. At the end, remove the # at the start of the last two lines, run again, and read from the error message why Python objects to the string.
Try it now· not graded; doesn't affect progress
Updating a price does not change the number of elements. But the customer's cart grows and shrinks: items are added, items are removed. For this we use the methods of the list. In lesson 21 you saw string methods: a dot and a function name after the value, like order.strip(). Lists have their own methods too. Each row in the table below starts from the same line: cart = ["latte", "cookie"].
| Method | What it does | Example | cart afterward |
|---|---|---|---|
append(x) | Adds to the end | cart.append("tea") | ['latte', 'cookie', 'tea'] |
insert(i, x) | Adds at position i, shifts the rest by one | cart.insert(0, "water") | ['water', 'latte', 'cookie'] |
remove(x) | Deletes the first element whose value is x | cart.remove("cookie") | ['latte'] |
pop() | Takes out the last element and returns it | last = cart.pop() |
A short note: cart + ["water"] joins two lists and gives a new list; it does not change cart. After new_cart = cart + ["water"], cart is still ['latte', 'cookie'] and new_cart is ['latte', 'cookie', 'water']. To make the cart itself longer we use append.
Keep three rules in mind when you use these methods.
Rule one: a method changes the list in place. Here there is a big difference from the string methods in lesson 21. A string does not change, so strip or upper returned a new string and you had to bind the result to a name. A list can change; cart.append("tea") changes cart itself. You do not need to assign the result anywhere; you write the line on its own.
Rule two: these methods return `None`, except `pop`. append, insert, and remove do their job and leave behind None, which means "nothing" (lesson 8). pop is the exception: it gives back the element it took out of the list. That is why last = cart.pop() is a meaningful line; the removed item is not lost, it is kept under the name last.
Rule three: `remove` deletes by value, `pop` deletes by position. cart.remove("cookie") says "find an item called cookie and delete it"; if the same item appears twice, it deletes only the first. cart.pop(0) says "take out whatever is at position 0". Deleting an item that is not there raises an error: ValueError: list.remove(x): x not in list. If you are not sure the item is in the cart, ask first: if item in cart:.
Example 3 (case): Updating the cart
cart = ["latte", "cookie"] cart.append("tea") cart.insert(0, "water") print(cart) cart.remove("cookie") last = cart.pop() print(cart, last) first = cart.pop(0) print(cart, first)
Output['water', 'latte', 'cookie', 'tea']
['water', 'latte'] tea
['latte'] waterinsert(0, "water") put water at the very start and shifted the other items by one position. remove found the cookie by its name and deleted it. pop() took out the tea at the end and gave it to last, and pop(0) took out the water at the start and gave it to first. If you need to turn the list into plain text to show it to the customer, the ", ".join(cart) you saw in lesson 21 still works.
Now try these methods with your own hands. Press the buttons below in any order; each time, see how the cart changes and what Python answers. The last button raises an error on purpose.
Touch the cart: which operation changes the list, and which only gives information?
Press an operation; predict what Python will say first.
No operations yet. Press a button above.
Follow the code below step by step. On each line, watch how the cart box changes, how the first box is filled from a read, and how the last box is filled from the value pop gives back.
Run the code line by line: see which line runs next, the variable boxes and the output.
cart = ["tea", "latte"] cart.append("bagel") first = cart[0] cart[1] = "mocha" last = cart.pop() print(cart) print(len(cart), first, last)
Now try out why the second rule matters. With string methods, binding the result to a name was right; what happens if you do the same with a list method?
What does this code print?
cart = ["latte"] cart = cart.append("water") print(cart)
Lists are used not only for carts but for anything where the order matters. At a gym, when the courts are full, members who arrive are written on a waiting list. A new arrival goes to the end of the queue, and when a court is free, the person at the front is called. Adding to the end is the job of append; taking out the person at the front and getting the name is the job of pop(0).
Example 4 (outside the case): A gym waiting list
waiting = ["Maya", "Leo"] waiting.append("Nina") next_up = waiting.pop(0) print("Next:", next_up) print("Waiting:", waiting, len(waiting))
OutputNext: Maya
Waiting: ['Leo', 'Nina'] 2Nina was added to the end, and Maya, first in line, left the list and moved to the name next_up. Leo is now at position 0; the next pop(0) will call him.
The register will add and remove items hundreds of times a day. As you have known since lesson 14, we put repeated work in a function. Here there is something specific to lists: if you give a function a list and the function changes that list inside, the list outside changes too. That is why the add_to_cart function does its job without returning anything; the items it adds stay in the caller's cart. We will see why this is so in lesson 25.
Example 5 (case): The lesson's target program
The steps of the two functions are named with comment lines. In the for i in range(qty): loop inside add_to_cart, i is never used; here it only counts the turns, and the loop runs qty times.
def add_to_cart(cart, item, qty=1): # 1. Add the item to the end as many times as requested for i in range(qty): cart.append(item) def remove_from_cart(cart, item): # 2. If there is one of the item, remove it and report the result if item in cart: cart.remove(item) return True return False cart = [] add_to_cart(cart, "latte") add_to_cart(cart, "cookie", qty=2) print("Cart:", cart) print("Removed?", remove_from_cart(cart, "cookie")) print("Removed?", remove_from_cart(cart, "water")) print("Cart:", cart) print(f"Items: {len(cart)} · First: {cart[0]} · Last: {cart[-1]}")
OutputCart: ['latte', 'cookie', 'cookie']
Removed? True
Removed? False
Cart: ['latte', 'cookie']
Items: 2 · First: latte · Last: cookieThe cart started as an empty list and was filled with two calls. qty=2 is the keyword argument from lesson 15; if it had not been given, the default 1 would have been used. remove_from_cart asks first and deletes after: if the item is not there, the remove line is never reached, and the program returns False without crashing. The caller can look at this answer and tell the customer "there is no water in your cart".
Below, change wanted and each time look at both the returned value and the final state of the cart. Notice how many items come out when the same item appears twice, and which lines never run when the item is not there.
When wanted changes, what does the function return and how does the cart end up?
Pick a value; predict the output first, then look.
1def remove_from_cart(cart, item):2 if item in cart:3 cart.remove(item)4 return True5 return False67cart = ["latte", "cookie", "cookie"]8wanted = "cookie"9print(remove_from_cart(cart, wanted), cart)
True ['latte', 'cookie']
Faded lines didn't run with this value. With two cookies, remove deletes only the first; one cookie stays in the cart. Because water is not in the cart, the body of the if (lines 3 and 4) never runs, the function returns False from line 5, and the cart stays as it was.
Now put the lines of the function in order yourself. Watch the indentation: which block should return False be inside?
Put the lines of the remove_from_cart function in the right order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
The online order arrives as a single line of text. The split from lesson 21 turns it into a list; now we can change that list. The customer wants mocha instead of tea and adds a bagel.
order = "latte,tea,water".split(",") order[1] = "mocha" order.append("bagel") print(order) print(", ".join(order))
Output['latte', 'mocha', 'water', 'bagel']
latte, mocha, water, bagelA student's to-do list. In the morning she adds breakfast to the very start, removes it from the list when she finishes it, cancels the workout, and changes the last task.
todo = ["homework", "gym", "groceries"] todo.insert(0, "breakfast") done = todo.pop(0) todo.remove("gym") todo[-1] = "bills" print("Done:", done) print("Remaining:", todo, len(todo))
OutputDone: breakfast
Remaining: ['homework', 'bills'] 2Assigning the result of a list method back to the list. As you are used to with string methods, you bind the result to the name, and on the next line the program crashes:
cart = ["latte"] cart = cart.append("water") cart.append("tea")
OutputAttributeError: 'NoneType' object has no attribute 'append'Read the message: an object of type NoneType has no attribute append. NoneType is the type of None. So when you reach the third line, the cart you hold is no longer a list but None: the append on the second line added the water but returned None, and the assignment bound the name cart to that None. The error shows up on the third line, but its cause is on the second line. The right way: call the list method on its own, cart.append("water"). The only method whose result you keep is pop
[...] and keeps many values in order; the index starts at 0, -1 is the end, a slice gives a new list and does not raise an error when it runs past the end, and len and in work as they do on strings.list[i] = x changes an existing position; append adds to the end, insert(i, x) adds in the middle; remove(x) deletes the first match by value, pop(i) deletes by position. Ask with in before deleting something that may not be there.None, so do not assign the result back to the list; pop returns what it took out. If a function changes the list it was given, the caller's list changes too.Next lesson: When the cart has 20 items, how will we find the total, the most expensive item, and the sorted version? In the next lesson we will loop over a list to build a summary and sort the list.
Exercises and quiz are for members
This lesson has 6 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
['latte'], last = 'cookie' |
pop(i) | Takes out the element at position i and returns it | first = cart.pop(0) | ['cookie'], first = 'latte' |
last = cart.pop()