Learn / Programming / Python / Lists and Tuples

Python · Lesson 6 of 15

Lists and Tuples

Ordered sequences — mutable lists vs immutable tuples.

  • Beginner
  • 16 min read
  • 3 objectives

Before this lessonLesson 5: Functions

What you will learn

  • Create and slice lists
  • Use list methods append/pop
  • Know when tuples beat lists

Lists and tuples are ordered sequences: they keep items in the order you put them in and let you fetch any item by its position. The difference is mutability. A list can be changed after creation; a tuple cannot.

Why we need collections

So far each variable held one value. Real data comes in groups: a list of prices, the days of the week, the pixels of an image. A list is a numbered row of boxes you can look through, add to and rearrange. Picture a shopping list on paper: items in order, you can cross one out, add another at the bottom, or read the third item.

Lists

Create a list with square brackets. Indexes start at 0, and negative indexes count from the end, so nums[-1] is the last item. Slicing with nums[start:stop] returns a new list that includes start and excludes stop.

nums = [10, 20, 30]
nums.append(40)      # add to the end
nums.insert(0, 5)    # add at a position
last = nums.pop()    # remove and return the last item

print(nums)
print(nums[1:3], nums[-1])
print(len(nums), 20 in nums)
Output
[5, 10, 20, 30]
[10, 20] 30
4 True

Other methods you will use constantly: remove(x), sort(), reverse(), index(x) and count(x). The built-in sorted(nums) returns a new sorted list and leaves the original alone.

Looping and comprehensions

A list comprehension builds a new list from an existing one in a single readable line: [expression for item in items if condition].

nums = [1, 2, 3, 4, 5, 6]
squares = [n * n for n in nums]
evens = [n for n in nums if n % 2 == 0]
print(squares)
print(evens)
Output
[1, 4, 9, 16, 25, 36]
[2, 4, 6]

Tuples

A tuple uses parentheses and cannot be modified. Use one for a small fixed group of related values, such as a coordinate pair or a database row. Because tuples are immutable, they can be used as dictionary keys.

point = (3, 4)
x, y = point        # unpacking
print(x, y, point[0])
# point[0] = 9      # TypeError: tuples are immutable
Output
3 4 3

Looping over a list

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit.upper())

print(len(fruits), "fruits")
Output
APPLE
BANANA
CHERRY
3 fruits

Adding, removing and searching

todo = ["email", "gym"]
todo.append("read")        # add at the end
todo.insert(1, "coffee")   # add at position 1
todo.remove("gym")         # remove by value
print(todo)
print("read" in todo)
print(todo.index("read"))
print(sorted(todo))
Output
['email', 'coffee', 'read']
True
2
['coffee', 'email', 'read']

Lists are shared, not copied

This trips up almost everyone. Assigning a list to another name does not copy it; both names label the same list. Change it through one name and the other sees the change. Use .copy() or a slice [:] for a real copy.

a = [1, 2, 3]
b = a            # same list!
b.append(4)
print(a)

c = a.copy()     # independent copy
c.append(5)
print(a, c)
Output
[1, 2, 3, 4]
[1, 2, 3, 4] [1, 2, 3, 4, 5]

Useful built-ins for numbers

scores = [72, 88, 95, 61]
print(sum(scores), min(scores), max(scores))
print(sum(scores) / len(scores))
scores.sort(reverse=True)
print(scores)
Output
316 61 95
79.0
[95, 88, 72, 61]

When to choose a tuple

A tuple is a list you promise not to change. Use it for things that belong together as one fixed record, like a coordinate (x, y) or an RGB colour (255, 0, 0). Because it cannot change, it is safe to use as a dictionary key, which a list is not.

point = (3, 4)
x, y = point        # unpacking
print(x, y)

visited = {(0, 0): "start", (1, 2): "shop"}
print(visited[(1, 2)])
Output
3 4
shop

Key takeaways

  • A list is an ordered, changeable collection; a tuple is ordered and fixed.
  • Indexes start at 0; negative indexes count from the end; slices take ranges.
  • append, insert, remove, pop, sort change a list in place.
  • Assignment shares a list; use .copy() when you need a separate one.
# Write your solution here
Up next · Lesson 7Dictionaries and SetsKey-value maps and unordered unique collections.