Python Lists

Keep many values in one variable, then read, change, add, remove and loop through them.

Lesson 19 of 107Beginner17 min read

So far each variable has held one value. But most programs deal with collections: a shopping list, the scores in a game, the names in a class. A list stores many values, in order, inside a single variable.

Lists are written with square brackets and commas, and they can grow, shrink and change while your program runs. They're one of the most used tools in Python, and they work perfectly with the for loops you learned in the last lesson.

In this lesson you'll create lists, read items by their position, change and remove items, slice out parts of a list and loop through every item.

Creating a list and reading items

Python
fruits = ["apple", "banana", "cherry"]
print(fruits[0])    # apple
print(fruits[2])    # cherry
print(len(fruits))  # 3
  • Each item has a position called an index. The first item is at index 0, not 1.
  • len() tells you how many items there are.
  • Negative indexes count from the end: fruits[-1] is the last item, fruits[-2] the one before it.
  • Asking for an index that doesn't exist, like fruits[3] here, causes an IndexError.

Changing, adding and removing

Lists are mutable, which means you can change them after creating them:

CodeWhat it does
fruits[1] = "kiwi"Replace the item at index 1
fruits.append("mango")Add an item to the end
fruits.insert(0, "lime")Insert an item at a position
fruits.remove("kiwi")Remove the first item with that value
fruits.pop()Remove and return the last item
"apple" in fruitsTrue if the item is in the list

Methods like append() change the list itself. You don't need to write fruits = fruits.append(...); in fact, doing that would replace your list with None.

Slicing

A slice copies part of a list. Write the start and stop index with a colon between them. As with range(), the stop index is not included:

Python
days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
print(days[1:3])   # ['Tue', 'Wed']
print(days[:2])    # ['Mon', 'Tue']
print(days[3:])    # ['Thu', 'Fri']

Leave out the start to begin at the front, or leave out the stop to go to the end. Slicing works on strings too: "Python"[0:3] is "Pyt".

Looping and useful functions

Python
scores = [72, 95, 88]

for score in scores:
    print(score)

print(sum(scores), max(scores), min(scores))
scores.sort()          # sorts the list in place
print(sorted(scores, reverse=True))  # a new sorted list

sum(), max() and min() work on any list of numbers. .sort() reorders the list itself, while sorted() gives you a new sorted list and leaves the original alone.

Copying a list and lists inside lists

Assigning a list to a second name does not copy it. Both names point to the same list, so a change through one name shows up through the other:

Python
original = [1, 2, 3]
alias = original
alias.append(4)
print(original)     # [1, 2, 3, 4]

copy = original.copy()   # or original[:] or list(original)
copy.append(5)
print(original)     # still [1, 2, 3, 4]

This surprises almost every beginner. Use .copy() whenever you want to change a list without affecting the original.

A list can contain other lists, which is a simple way to store a grid or a table. Use two indexes: the first picks the row, the second picks the item in that row.

Python
seats = [
    ["A1", "A2", "A3"],
    ["B1", "B2", "B3"],
]
print(seats[1][0])   # B1

.copy() only copies the outer list; the inner lists are still shared. For nested data, copy.deepcopy() from the copy module makes a fully independent copy.

More list methods worth knowing

MethodWhat it does
items.extend(other)Add every item from another list to the end
items.index(value)Position of the first matching item (ValueError if absent)
items.count(value)How many times a value appears
items.reverse()Reverse the list in place
items.clear()Remove every item
items.sort(key=len)Sort using a rule, here by length

The key argument works with both sort() and sorted(). key=str.lower sorts words alphabetically without capital letters jumping to the front.

Python Lists Syntax

Common list operations

items = [value1, value2, value3]
items[0]              # first item
items[-1]             # last item
items.append(value)   # add to end
items.remove(value)   # remove by value
items[1:3]            # slice
len(items)            # number of items
for item in items:
    print(item)

Python Lists Summary

  • A list is an ordered collection in square brackets: [1, 2, 3].
  • Indexes start at 0; -1 is the last item. len() counts items.
  • append(), insert(), remove() and pop() change the list.
  • list[start:stop] slices out a part; the stop index isn't included.
  • for item in my_list: visits every item in order.

Python Lists Examples

Each example shows the code, the output it produces and what each part does.

Example 1

A shopping list

Python
shopping = ["milk", "bread", "eggs"]

shopping.append("apples")
shopping.remove("bread")
shopping[0] = "oat milk"

print(shopping)
print("Items to buy:", len(shopping))
print("Last item:", shopping[-1])
Output
['oat milk', 'eggs', 'apples']
Items to buy: 3
Last item: apples
Line-by-line explanation
  1. Line 3append() adds "apples" to the end.
  2. Line 4remove() takes out "bread", so later items move up one place.
  3. Line 5Index 0 is replaced with a new value.
  4. Line 9-1 always means the last item.
Example 2

Class results

Python
scores = [64, 91, 78, 85, 55]

print("Highest:", max(scores))
print("Lowest:", min(scores))
average = sum(scores) / len(scores)
print(f"Average: {average:.1f}")

passed = 0
for s in scores:
    if s >= 60:
        passed += 1
print(f"{passed} of {len(scores)} passed")
Output
Highest: 91
Lowest: 55
Average: 74.6
4 of 5 passed
Line-by-line explanation
  1. Lines 3 to 4max() and min() find the extremes without a loop.
  2. Line 5The average is the total divided by how many scores there are.
  3. Lines 8 to 11Loop through each score and count the ones that are 60 or more. Only 55 falls short.
Example 3

Top three with sorting and slicing

Python
players = ["Ana", "Ben", "Cleo", "Dev", "Eli"]
points = [40, 75, 60, 90, 55]

ranked = sorted(points, reverse=True)
print("Top three scores:", ranked[:3])

for i in range(len(players)):
    print(f"{players[i]}: {points[i]}")
Output
Top three scores: [90, 75, 60]
Ana: 40
Ben: 75
Cleo: 60
Dev: 90
Eli: 55
Line-by-line explanation
  1. Line 4sorted() returns a new list from highest to lowest; points itself is unchanged.
  2. Line 5The slice [:3] takes the first three items.
  3. Lines 7 to 8range(len(players)) gives the indexes 0 to 4, so the same index can read both lists.

Common Python Lists Mistakes

Starting to count at 1

Don't
colors = ["red", "green", "blue"]
print(colors[3])   # IndexError
Do
colors = ["red", "green", "blue"]
print(colors[2])   # blue, the third item

Saving the result of append()

Don't
names = ["Ada"]
names = names.append("Alan")
print(names)   # None
Do
names = ["Ada"]
names.append("Alan")
print(names)   # ['Ada', 'Alan']

append() changes the list and returns None, so assigning its result throws your list away.

Removing a value that isn't there

Don't
pets = ["cat", "dog"]
pets.remove("fish")   # ValueError
Do
pets = ["cat", "dog"]
if "fish" in pets:
    pets.remove("fish")

Python Lists in Real Projects

Lists in real programs

A to-do app keeps tasks in a list and appends new ones, a music player stores the queue of songs, and a data script reads every row of a spreadsheet into a list before calculating totals. When you later read data from files or websites, it very often arrives as a list.

Python Lists FAQ

What is the difference between append() and extend()?

append() adds one item, even if that item is a list: [1, 2].append([3, 4]) gives [1, 2, [3, 4]]. extend() adds each item from another sequence: [1, 2].extend([3, 4]) gives [1, 2, 3, 4]. Both change the list in place and return None.

How do I check if a Python list is empty?

An empty list is falsy, so write if not items: to test for empty and if items: to test for at least one item. This is the style recommended by Python's PEP 8 guide.

How do I remove duplicates from a list but keep the order?

list(dict.fromkeys(items)) keeps the first occurrence of each value in its original order, because dictionary keys are unique and remember insertion order. list(set(items)) also removes duplicates, but the order is not guaranteed.

Is a Python list the same as an array?

A Python list is a flexible, resizable sequence that can hold any mix of types. Languages such as Java and C have fixed-size arrays of one type. Python has an array module and the NumPy library for compact numeric arrays, but for everyday programming a list is what you use.

Why did changing one list change another one too?

Both variables refer to the same list object, usually because you wrote b = a. Make a real copy with b = a.copy() or b = a[:]. For a list that contains other lists, use copy.deepcopy(a).

Python Lists Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Complete the code so "pear" is added to the end of the list.

fruit = ["apple", "plum"]
fruit.("pear")
print(fruit)
Predict the outputeasy

What does this print?

letters = ["a", "b", "c", "d"]
print(letters[1], letters[-1])
Predict the outputmedium

What does this print?

nums = [10, 20, 30, 40, 50]
print(nums[1:4])
Multiple choicemedium

Which line removes and returns the last item of a list called stack?

Predict the outputmedium

What does this print?

nums = [4, 8, 15, 16, 23]
print(nums[1:3], nums[-1])

Python Lists Quiz

5 questions to check what you learned.

  1. What is the index of the first item in a Python list?

    • 1
    • 0
    • -1
    • It depends on the list
  2. What does len(["x", "y", "z"]) return?

    • 2
    • "xyz"
    • 0
    • 3
  3. What's the difference between my_list.sort() and sorted(my_list)?

    • There is no difference
    • sorted() changes the list itself; sort() returns a new list
    • sort() changes the list itself; sorted() returns a new sorted list
    • sort() only works on numbers
  4. What is ["a", "b", "c", "d", "e"][-2:]?

    • ['d', 'e']
    • ['d']
    • ['c', 'd']
    • ['e']
  5. What's the difference between append and extend?

    • There's none
    • extend adds to the front
    • append sorts the list
    • append adds one item; extend adds every item from another list