Python Lists · Examples
Beginner

Python Lists Examples

Short, runnable programs that show python lists in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python Lists lesson.

1Sum, minimum and maximum of a list

Built-in functions work directly on lists of numbers.

Sum, minimum and maximum of a list
temps = [21, 25, 19, 30, 24]
print("Total:", sum(temps))
print("Coldest:", min(temps))
print("Hottest:", max(temps))
print("Average:", sum(temps) / len(temps))
Expected outputTotal: 119
Coldest: 19
Hottest: 30
Average: 23.8

2Sorting a list

sorted() returns a new sorted list; .sort() sorts the list in place.

Sorting a list
names = ["Zoe", "adam", "Maya"]
print(sorted(names))
print(sorted(names, key=str.lower))
names.sort(reverse=True)
print(names)
Expected output['Maya', 'Zoe', 'adam']
['adam', 'Maya', 'Zoe']
['adam', 'Zoe', 'Maya']

3Checking membership with in

in tells you whether a value is somewhere in the list.

Checking membership with in
allowed = ["admin", "editor"]
role = "viewer"
if role in allowed:
    print("Access granted")
else:
    print("Access denied for", role)
Expected outputAccess denied for viewer

4Nested lists (a small grid)

A list can contain lists. Use two indexes: row first, then column.

Nested lists (a small grid)
grid = [
    [1, 2, 3],
    [4, 5, 6],
]
print(grid[1])
print(grid[1][2])
for row in grid:
    print(sum(row))
Expected output[4, 5, 6]
6
6
15

Practise next

Python Lists exercises → Back to the lesson

Python List Methods examplesPython Slicing examplesPython Tuples examplesPython List Comprehensions examples