Cohort 4Register

PART 1 · PYTHON FROM ZERO · LESSON 10

Lists: ordered collections

FreeLesson 12 of 78

A list holds many values in order, in one variable. It is the first data structure you need and the one you will use most.

CREATE, ADD, REMOVE, CHANGEPYTHON 3.12
cities = ["Bengaluru", "Mumbai", "Delhi"]
print(cities[0], cities[-1], len(cities))

cities.append("Pune")            # add to the end
cities.insert(1, "Chennai")      # add at position 1
print(cities)

cities.remove("Delhi")           # remove by value
last = cities.pop()              # remove and return the last item
print(cities, "| popped:", last)

cities[0] = "Bangalore"          # change an item
print(cities, "Mumbai" in cities)

Output

Bengaluru Delhi 3
['Bengaluru', 'Chennai', 'Mumbai', 'Delhi', 'Pune']
['Bengaluru', 'Chennai', 'Mumbai'] | popped: Pune
['Bangalore', 'Chennai', 'Mumbai'] True
SUM, SORT, SLICEPYTHON 3.12
amounts = [1198, 796, 1499, 1999, 1348]
print(sum(amounts), min(amounts), max(amounts))
print(sorted(amounts))                  # a new, sorted list
print(sorted(amounts, reverse=True)[:3])  # top 3
print(amounts[1:3], amounts[::-1])      # slice, reversed

amounts.sort()                          # sorts this list in place
print(amounts)

big = [a for a in amounts if a > 1300]  # see page 30

print(big)

Output

6840 796 1999
[796, 1198, 1348, 1499, 1999]
[1999, 1499, 1348]
[796, 1499] [1348, 1999, 1499, 796, 1198]
[796, 1198, 1348, 1499, 1999]
[1348, 1499, 1999]
A TABLE AS A LIST OF LISTSPYTHON 3.12
orders = [
    [101, "Aarav", 1198],          # a list of lists:
    [102, "Diya", 796],            # each inner list is one row
    [103, "Aarav", 1499],
]
for order_id, name, amount in orders:     # unpack each row
    print(order_id, name, amount)
print(orders[2][1])                        # row 2, column 1

Output

101 Aarav 1198
102 Diya 796
103 Aarav 1499
Aarav

A list of rows is how a small table looks in plain Python. Later you will use a list of dicts (Lesson 12), which names each column instead of relying on positions.

MethodDoesExample
append(x)Add one item to the endxs.append(5)
extend(other)Add every item of another listxs.extend([6, 7])
insert(i, x)Add at a positionxs.insert(0, 1)
remove(x) / pop(i)Delete by value / by positionxs.remove(5); xs.pop(0)
index(x) / count(x)Where is x? How many times?xs.index(7); xs.count(7)
sort() / reverse()Reorder in placexs.sort(reverse=True)
copy() / clear()New copy / empty itys = xs.copy()

Try it yourself before moving on

  1. Add three cities to an empty list and print them sorted.
  2. Print the second-largest amount in a list.
  3. Remove every "cancelled" from a list of statuses by building a new list.

Watch the free lesson

The same topic in the Free Lessons library, free with a sign-in.