Lesson 8 of 12

Python Lists and Tuples

Programs rarely deal with one value at a time. A shop has many products, a class has many students, a month has many expenses. A list keeps many values in order inside one variable, and a tuple does the same for values that should not change. Together with the loops from Python Loops, Python lists and tuples let you process any amount of data with a few lines of code.

Creating and reading Python lists

Write a list with square brackets and commas between items. A list can hold any types, even a mix, but in practice most lists hold items of one kind. Lists use the same indexing and slicing as strings: the first item is at index 0, the last at -1, and len() gives the number of items.

snacks = ["murukku", "samosa", "bajji", "vada", "bonda"]

print(snacks[0])
print(snacks[-1])
print(snacks[1:3])
print(len(snacks))

snacks[2] = "paniyaram"
print(snacks)
print("vada" in snacks)
Output
murukku
bonda
['samosa', 'bajji']
5
['murukku', 'samosa', 'paniyaram', 'vada', 'bonda']
True

Unlike strings, Python lists are mutable: you can change an item in place, as the line snacks[2] = "paniyaram" does.

Adding and removing items

MethodWhat it does
items.append(x)Adds x to the end
items.insert(i, x)Inserts x before index i
items.extend(other)Adds every item of another list
items.remove(x)Removes the first item equal to x (error if missing)
items.pop() / items.pop(i)Removes and returns the last item, or the item at i
del items[i]Deletes the item at index i
items.index(x), items.count(x)Position of x; how many times it appears
cart = ["rice", "dal"]
cart.append("ghee")
cart.insert(0, "jaggery")
cart.extend(["cardamom", "cashews"])
print(cart)

cart.remove("dal")
last = cart.pop()
print("Removed:", last)
print(cart)
print(cart.index("ghee"))
Output
['jaggery', 'rice', 'dal', 'ghee', 'cardamom', 'cashews']
Removed: cashews
['jaggery', 'rice', 'ghee', 'cardamom']
2

Sorting and summarising

items.sort() sorts the list itself and returns None. sorted(items) leaves the original alone and returns a new sorted list. Both accept reverse=True, and a key function that decides what to sort by, such as key=len to sort words by length. For lists of numbers, the built-ins sum(), min() and max() do the common maths in one call.

expenses = [1200, 350, 4800, 999, 150]

print(sorted(expenses))
print(expenses)
expenses.sort(reverse=True)
print(expenses)

print("Total:", sum(expenses))
print("Biggest:", max(expenses), "Smallest:", min(expenses))
print(f"Average: {sum(expenses) / len(expenses):.2f}")

cities = ["Ooty", "Coimbatore", "Salem", "Erode"]
print(sorted(cities, key=len))
Output
[150, 350, 999, 1200, 4800]
[1200, 350, 4800, 999, 150]
[4800, 1200, 999, 350, 150]
Total: 7499
Biggest: 4800 Smallest: 150
Average: 1499.80
['Ooty', 'Salem', 'Erode', 'Coimbatore']

Look at the last line of output. "Salem" and "Erode" both have five letters, and they stay in their original order. Python’s sorting is stable: items that compare equal never swap places, which matters when you sort data by one column after another.

Watch out: A common bug is expenses = expenses.sort(). Because sort() returns None, the list is lost. Either call expenses.sort() on its own line or use expenses = sorted(expenses).

List comprehensions

A list comprehension builds a new list from another in a single line: [expression for item in items if condition]. It does the same job as a for loop with append(), but it is shorter and, once you are used to it, easier to read. For example, [p * 1.18 for p in prices] adds 18% GST to every price, and [p for p in prices if p < 500] keeps only the cheaper items. Keep comprehensions simple; if one needs several conditions or nested loops, a normal loop is clearer.

Copying lists safely

Assigning a list to a second name does not copy it. backup = cart makes both names point to the same list, so changing one changes the other. To make an independent copy, use cart.copy(), list(cart) or cart[:].

Tuples

A tuple is like a list that cannot be changed after it is created. Write it with round brackets: location = (11.93, 79.83). A tuple with one item needs a trailing comma: ("Chennai",). Use tuples for fixed groups of values, such as coordinates, a date or a record of (name, price). Because they cannot change, tuples protect data from accidental edits, and they can be used as dictionary keys, which lists cannot.

Unpacking assigns the items of a tuple (or list) to several variables at once, as you did for swapping in Python Syntax and Variables. A star collects “the rest” into a list.

prices = [120, 450, 899, 60]
with_gst = [round(p * 1.18, 2) for p in prices]
cheap = [p for p in prices if p < 500]
print(with_gst)
print(cheap)

cart = ["rice", "dal"]
alias = cart
snapshot = cart.copy()
cart.append("salt")
print(alias, snapshot)

puducherry = (11.93, 79.83)
lat, lon = puducherry
print(f"Latitude {lat}, longitude {lon}")

first, *others = ["Gold", "Silver", "Bronze", "Fourth"]
print(first, others)
Output
[141.6, 531.0, 1060.82, 70.8]
[120, 450, 60]
['rice', 'dal', 'salt'] ['rice', 'dal']
Latitude 11.93, longitude 79.83
Gold ['Silver', 'Bronze', 'Fourth']

Tip: Trying to change a tuple, as in puducherry[0] = 12, raises TypeError: 'tuple' object does not support item assignment. If you need to change the values, convert it with list() or simply create a new tuple.

Further reading

Key takeaways

  • Lists [ ] are ordered and changeable; tuples ( ) are ordered and fixed.
  • Add with append, insert and extend; remove with remove, pop and del.
  • sort() changes the list and returns None; sorted() returns a new list.
  • List comprehensions build new lists in one readable line.
  • b = a does not copy a list; use a.copy(). Unpack tuples with x, y = point.

Quick quiz

Check what you learned – pick an answer.

1. nums = [5, 3, 8]; nums.append(1). What is nums?

2. What does [n * 2 for n in range(4)] produce?

3. Which line creates a tuple with one item?

Practice exercise

Given marks = [78, 92, 45, 66, 88, 39], use a list comprehension to make a list of passing marks (40 or more), then print it sorted from highest to lowest, with the count and the average of the passing marks.

Show a hint

Filter with if m >= 40 inside the comprehension, then use sorted(..., reverse=True), len() and sum().

Show the solution
marks = [78, 92, 45, 66, 88, 39]

passed = [m for m in marks if m >= 40]
print(sorted(passed, reverse=True))
print("Passed:", len(passed))
print(f"Average: {sum(passed) / len(passed):.1f}")

Progress is saved in this browser only.