Tutorials › Python Tutorial › Python Lists

Python Lists

10 min read · Lesson 10 of 24

So far each variable has held one value. Real programs deal with many: all the students in a class, every sale today, the stops on a matatu route. A list stores many values, in order, under a single name.

Creating a list

Write the items inside square brackets, separated by commas.

Example PYTHON
stops = ["Kencom", "Ngara", "Pangani", "Thika Road Mall"]
prices = [50, 70, 70, 100]
mixed = ["Wanjiku", 27, True, 61.5]
empty = []
print(stops)
print(prices)
print(mixed)
print(empty)
Result
['Kencom', 'Ngara', 'Pangani', 'Thika Road Mall']
[50, 70, 70, 100]
['Wanjiku', 27, True, 61.5]
[]
Try it Yourself »

Lists have these key properties:

  • Ordered – items keep the order you put them in.
  • Changeable – you can add, remove and replace items.
  • Allow duplicates – the same value can appear more than once (70 appears twice above).
  • Any type – a list can hold strings, numbers, other lists, anything.

Accessing items

Each item has an index, starting at 0, just like characters in a string.

Example PYTHON
stops = ["Kencom", "Ngara", "Pangani", "Thika Road Mall"]
print(stops[0])
print(stops[2])
print(stops[-1])
Result
Kencom
Pangani
Thika Road Mall
Try it Yourself »
Warning: Asking for an index that does not exist, like stops[10], raises an IndexError: list index out of range. Use len() to know how many items there are.

Length of a list

Example PYTHON
stops = ["Kencom", "Ngara", "Pangani", "Thika Road Mall"]
print(len(stops))
Result
4
Try it Yourself »

Changing an item

Assign a new value to an index to replace that item.

Example PYTHON
scores = [56, 72, 64]
scores[1] = 80
print(scores)
Result
[56, 80, 64]
Try it Yourself »

Checking if an item exists

Example PYTHON
fruits = ["mango", "pawpaw", "banana"]
if "mango" in fruits:
    print("Yes, we have mangoes.")
print("avocado" in fruits)
Result
Yes, we have mangoes.
False
Try it Yourself »

Looping through a list

A for loop visits each item in turn. This is the most common thing you will do with a list.

Example PYTHON
team = ["Akinyi", "Mutua", "Chebet"]
for person in team:
    print("Hello,", person)
Result
Hello, Akinyi
Hello, Mutua
Hello, Chebet
Try it Yourself »

If you also need the position, use enumerate(). Loops are covered fully in Python For Loops.

Example PYTHON
team = ["Akinyi", "Mutua", "Chebet"]
for number, person in enumerate(team, start=1):
    print(number, person)
Result
1 Akinyi
2 Mutua
3 Chebet
Try it Yourself »

Useful functions for number lists

Python's built-in functions make simple statistics easy:

Example PYTHON
sales = [1200, 3400, 950, 2100, 1800]
print("Total:", sum(sales))
print("Highest:", max(sales))
print("Lowest:", min(sales))
print("Average:", sum(sales) / len(sales))
Result
Total: 9450
Highest: 3400
Lowest: 950
Average: 1890.0
Try it Yourself »

Lists inside lists

A list can contain other lists. This is a simple way to store table-like data.

Example PYTHON
marks = [
    ["Amina", 78],
    ["Kiprop", 85],
    ["Njeri", 91],
]
print(marks[1])
print(marks[1][0])
print(marks[2][1])
Result
['Kiprop', 85]
Kiprop
91
Try it Yourself »

marks[1][0] means "item 1 of the outer list, then item 0 of that inner list".

Creating a list with list()

The list() function turns other collections into a list:

Example PYTHON
print(list("Embu"))
print(list(range(5)))
Result
['E', 'm', 'b', 'u']
[0, 1, 2, 3, 4]
Try it Yourself »

When should you use a list?

Reach for a list whenever you have a group of similar things and their order matters, or when the group will grow and shrink while the program runs. A queue of customers at a bank, the readings from a rain gauge taken every hour, or the names on a class register are all natural lists.

If the values should never change after you create them, a tuple is a better fit. If you only care about which items are present and want duplicates removed, use a set. If each value needs a label, such as a name and a phone number for every contact, a dictionary is the right tool.

Tip: Give list variables plural names (stops, prices, students). Then a loop reads naturally: for student in students:.

Exercises

Exercise

Print the second item of the list.

towns = ["Nyeri", "Meru", "Embu"]
print(towns[])
Exercise

Print how many items are in the list.

print((towns))

Next: add, remove and slice items in Python List Methods and Slicing.

Sign in or create a free account to track progress, earn XP, badges and a certificate.