Chapter 7

Lists

Store and manage many values together using Python lists.

A list stores several values in one ordered container. You write a list with square brackets and separate items with commas.

fruits = ['apple', 'banana', 'cherry']
numbers = [4, 8, 15]

Accessing items

Like strings, list positions start at 0, and negative indexes count from the end:

fruits = ['apple', 'banana', 'cherry']
print(fruits[0])    # apple
print(fruits[-1])   # cherry
print(len(fruits))  # 3

Changing a list

Lists are mutable, meaning you can change them in place:

fruits[1] = 'mango'          # replace an item
fruits.append('grape')       # add to the end
fruits.remove('apple')       # delete a value

append() adds one item at the end, and remove() deletes the first matching value.

Slicing lists

A slice returns part of the list. The end position is excluded:

numbers = [4, 8, 15, 16, 23]
print(numbers[1:3])   # [8, 15]

Looping over a list

A for loop is the natural way to visit every item:

for fruit in fruits:
    print(fruit)

Checking membership

The in keyword tests whether a value is present:

print('mango' in fruits)   # True or False

Adding and inserting

Besides append(), you can put an item at a chosen position with insert():

letters = ['a', 'c']
letters.insert(1, 'b')
print(letters)   # ['a', 'b', 'c']

Sorting and counting

  • sort() arranges items in order.
  • count(x) tells how many times x appears.
  • sum() and max() work on lists of numbers.
marks = [50, 90, 70]
marks.sort()
print(marks)        # [50, 70, 90]
print(sum(marks))   # 210
print(max(marks))   # 90

Making an empty list

A common pattern is to start empty and add items inside a loop:

squares = []
for n in range(1, 4):
    squares.append(n * n)
print(squares)   # [1, 4, 9]

Lists can hold anything

A single list can mix types, and a list can even contain other lists:

mixed = [1, 'two', 3.0, True]
grid = [[1, 2], [3, 4]]
print(grid[0][1])   # 2

To copy a list without linking the two names together, use a full slice or the list() function, because a plain assignment just makes a second name for the same list.

Remember

  • List indexes start at 0.
  • append() adds one item; remove() deletes by value.
  • Lists can be changed after they are created.

Stuck on this topic? A verified JomKelas tutor can walk you through it.

Find a verified tutor