Lists: Beginner
The brackets mark where the list starts and ends, and each comma separates 1 item from the next. scores holds 3 integers, days holds 4 strings, prices holds 3 floats, and empty holds nothing at all, which still counts as a list.
print shows the whole list in its bracket form, so every item is visible at once. len counts the items and returns 3 for scores. type(scores) == list is True, the same way type(88) == int and type("Mon") == str are both True. A list is a type of its own, and the values inside it keep their own types.
Items keep their order
Any type can go inside
Python prints strings inside a list with single quotes, even when you typed double quotes. Both spellings make the same string, and the quotes are part of the display rather than part of the value.
| List | Items | len() |
|---|---|---|
| [88, 92, 75] | 3 integers | 3 |
| ["Mon", "Tue"] | 2 strings | 2 |
| ["Ada", 34, True] | a string, an int and a bool | 3 |
| [4.99] | 1 float | 1 |
| [] | nothing | 0 |
scores, cities, prices. A loop variable can then take the singular for city in cities so the code reads as a sentence.- ▸Square brackets open and close a list; commas separate the items.
- ▸Items keep the order they were written in, and a for loop visits them in that order.
- ▸Any type can go inside, and types can mix within 1 list.
- ▸
len(items)returns the count, which is 0 for[].
len gives you a number
len returns an ordinary integer, so you can store it, do arithmetic with it or test it in an if like any other number. A small hotel keeps its booked guests and its waiting list as 2 separate lists. The front desk wants the total of both and the gap between them, and it also wants to know how many of its 5 rooms are still free.
An empty list adds 0 to any total, so a sum of lengths counts exactly the items present. If the waiting list were [], the first line would print 3 and the second would print 3 as well.
What does this program print?
| Item | Mon | Tue | Wed | Thu |
|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 |
| Negative index | -4 | -3 | -2 | -1 |
days[0] is an expression with a value, so it goes anywhere a value goes: inside print, on the right of an assignment, or joined to another string with +. The index can be a variable too: with i = 2, days[i] is "Wed".
Counting from the end
Past the end
Run, this program prints blue and then stops with a traceback whose last line is IndexError: list index out of range. The word done never prints. That message always means the number in the brackets was too large for the list, or too negative: index -4 on this 3-item list fails the same way. Section 4 shows how to check before asking.
Replacing an item
1planets = ["Mercury", "Venus", "Mars", "Jupiter"]2print("Before:", planets)34# Fix: Earth should be at index 25planets[2] = "Earth"6print("After:", planets)78# Update the first planet9planets[0] = "MERCURY"10print("Final:", planets)
Index plus loop
range(len(...)) only when the position matters. When you only need the items, for task in tasks is the clearer loop, and it can't go out of range.What does this program print?
The third item is at index 2
1shopping = ["milk", "bread"]2print("Before:", shopping)34shopping.append("eggs")5print("After first append:", shopping)67shopping.append("cheese")8print("After second append:", shopping)910shopping.append("butter")11print("Final:", shopping)
Building a list in a loop
1squares = []23for num in range(1, 6):4 squared = num * num5 squares.append(squared)67print(squares)
1source = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]2evens = []34for number in source:5 if number % 2 == 0:6 evens.append(number)78print(evens)
- ▸Create an empty list before the loop starts.
- ▸Compute 1 value on each pass through the loop.
- ▸Append it, optionally only when an
iftest passes. - ▸Use the finished list after the loop ends.
Inserting at a position
1letters = ["a", "c", "d"]2print("Before:", letters)34# Insert "b" at index 15letters.insert(1, "b")6print("After insert at 1:", letters)
1queue = ["second", "third", "fourth"]2print("Before:", queue)34# Insert at the beginning5queue.insert(0, "first")6print("After:", queue)
- Adds at the end
- Takes 1 argument
- Never shifts other items
- Use when arrival order is the order you want
- Adds at a chosen index
- Takes 2 arguments, index first
- Shifts later items right by 1
- Use when the position must be chosen
items.append(x) on its own line rather than items = items.append(x), which throws the list away.Index first, item second
insert reads its first argument as the position and its second as the item, always in that order. On a list of numbers, swapping them raises no error: both arguments are integers, so Python accepts either order and quietly does something else.
The first call puts 5 at the front. The second puts 0 at the end, because index 5 lies beyond the end of a 3-item list. With a string item the swap fails loudly instead: an index must be a whole number, so names.insert("Zed", 0) raises a TypeError before the list changes.
remove: by value
1groceries = ["milk", "eggs", "bread", "eggs", "cheese"]2print("Before:", groceries)34groceries.remove("eggs")5print("After removing eggs:", groceries)
When run, the program prints ['ink']. Then it stops with a traceback ending in ValueError: list.remove(x): x not in list. The first remove succeeded, so the second found no "pen" left and the last print never ran. The error names the problem as a value problem, which separates it from the index problems below.
pop: by index, with a return
1stack = ["first", "second", "third", "fourth"]2print("Before:", stack)34# Pop without argument removes last item5last = stack.pop()6print("Popped:", last)7print("After pop():", stack)89# Pop with index removes specific item10middle = stack.pop(1)11print("Popped index 1:", middle)12print("Final:", stack)
pop() with no argument removes the last item and returns it. pop(1) does the same for index 1. Either way the removed item comes back, so you can store it in a variable or print it, as the animation does with last and middle.
On a list of numbers, remove and pop look alike, since each takes a number in parentheses. remove reads the number as a value to find, and pop reads it as a position.
a.remove(2) deleted the first 2 it found, which sat at index 1. b.pop(2) went to index 2 and took 9, leaving both 2s in place. The method in front of the parentheses decides what the number means.
del: by index, no return
1numbers = [10, 20, 30, 40, 50]2print("Before:", numbers)34del numbers[2]5print("After del [2]:", numbers)67del numbers[0]8print("After del [0]:", numbers)
| Tool | You give | You get back | Fails when |
|---|---|---|---|
| groceries.remove("eggs") | a value | nothing | the value is absent (ValueError) |
| stack.pop() | an optional index | the removed item | the list is empty or the index is out of range, too large or too negative (IndexError) |
| del numbers[2] | an index | nothing | the index is out of range, too large or too negative (IndexError) |
What does this program print?
Choosing among remove, pop and del
Pick the tool by what you have in hand. If you know the value, such as a guest's name, use remove. pop fits when you know the position and need the item afterwards, and it also takes negative indexes. When you know the position and have no further use for the item, del is enough.
Check the length before indexing
Check for empty before pop
A loop that pops on every pass needs the list to still have items. Testing len(inbox) > 0 before each pop turns the third and fourth passes into a message instead of a crash.
Count before remove
Guarding the first and last item
items[0] and items[-1] name positions every non-empty list has, but an empty list has neither a first nor a last item, so both raise IndexError on []. The guard is the same emptiness test used before pop: check the length, then read.
Wrap it in a function
1def safe_get(items, index, fallback):2 if index >= 0 and index < len(items):3 return items[index]4 return fallback56queue = ["intro", "verse", "chorus"]7print(safe_get(queue, 1, "silence"))8print(safe_get(queue, 3, "silence"))9print(safe_get(queue, -1, "silence"))
The function returns the item when the index is in range and the fallback otherwise.
- Compare the index against len() before reading from the list
- Test len(items) > 0 before every pop()
- Test count(value) > 0 before remove(value)
- Return a fallback from a helper so callers always get a value
- Assume a list still has items inside a loop that pops
- Hard-code an index like 3 without checking the length
- Call remove on a value you never confirmed is present
- Let a number from outside the program reach [] unchecked
What does this program print?
> A pizza shop runs its kitchen from a list of order numbers. New orders append to the end, a phoned-in rush order inserts at index 0, the cook pops index 0 to start the next pizza, and a cancelled order is removed by its number. At closing time the display reads index 0 for the next order, and on an empty list that read would crash the screen.
len() counts them.items[i] = value replaces an item in place without changing the length.append adds at the end and insert(index, item) adds at a position, shifting later items right.remove deletes by value, pop deletes by index and returns the item, del deletes by index and returns nothing.count check.Lists hold values in order, so you can read, replace, add and remove them by position or by value.
- Category
- Python
- Difficulty
- beginner
- Duration
- 46 minutes
- Challenges
- 20 hands-on challenges
Topics covered: Creating Lists, Accessing Items by Index, Adding Items to Lists, Removing Items from Lists, Safe List Access
Lesson Sections
- Creating Lists (concepts: Lists)
A list holds any number of values in one variable, in the order you wrote them. Where a plain variable stores 1 score, a list stores 3 scores or 300 of them and keeps track of which came first. Python writes a list as square brackets around values separated by commas. Items keep their order A list remembers the sequence you gave it. A for loop visits each item from first to last, the same way it walks through range, except the loop variable receives the item itself rather than a count. The list
- Accessing Items by Index
Every item in a list sits at a numbered position called its index, and the numbering starts at 0. The first item is at index 0, the second at index 1, and the last item of a list with 4 items is at index 3. To read an item, write the list's name followed by the index in square brackets. Counting from the end A negative index counts backwards from the end. Index -1 is the last item, -2 the one before it, and -4 is the first item of a 4-item list. This saves working out the length first: the last
- Adding Items to Lists (concepts: List Modification)
Lists change size while a program runs. The append method adds 1 item to the end, in place: the list itself grows and no new list comes back. Call it with a dot after the list's name and the new item in parentheses. After 3 calls, shopping holds 5 items, each new one landing after the previous. The order of the calls becomes the order in the list, so append is the right tool whenever items arrive one at a time and arrival order is the order you want to keep. Building a list in a loop The most co
- Removing Items from Lists (concepts: List Modification)
Each way of taking items out of a list differs in what you give it and what you get back. remove takes a value and returns nothing. pop and del both take an index, but only pop hands the removed item back. Pick by what you know: the value, or the position. remove: by value groceries held "eggs" twice, and only the first one went. remove searches from the front, deletes the first match and stops. A second remove("eggs") would delete the other one, and a third would fail, because the value is no l
- Safe List Access (concepts: List Modification)
Reading an index that doesn't exist, popping from an empty list and removing a value that is not there all stop a program. Each has a check that costs 1 line and runs before the risky call, so the program prints a message and carries on instead of ending with a traceback. Check the length before indexing A list of n items accepts indexes 0 through n - 1. An index is safe when it's below len(items), and, for counting from the front, at least 0. Compare first, read second. The else branch prints a