← All lessons

Lesson 7 of 18 · about 16 minutes

Lists and Tuples 📋

A list is an ordered collection you can change. It is the workhorse of Python.

crew = ["Ada", "Alan", "Grace"]
crew.append("Linus")        # add to end
crew.insert(0, "Guido")     # add at position
crew.remove("Alan")         # remove by value
last = crew.pop()           # remove and return last
print(len(crew), crew[0], crew[-1])
print("Ada" in crew)        # True

Sorting and slicing

nums = [5, 2, 9, 1]
nums.sort()                 # changes the list: [1,2,5,9]
print(sorted(nums, reverse=True))   # new list
print(nums[1:3])            # [2, 5]

Tuples: lists that cannot change

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

Looping over lists

prices = [3.5, 8, 12.25]
total = sum(prices)
for p in prices:
    print(f"£{p:.2f}")
💡 Copy a list with new = old[:] or old.copy(). new = old just makes a second name for the same list.

Your challenge

Start with scores = [88, 42, 95, 67, 73]. Print the highest score, the lowest score, the average rounded to 1 decimal place, and finally the list sorted from high to low.