Lesson 1 of 5 · Collections · 3 min read · Updated

Working with lists

Adding, removing, sorting and copying — the list methods you will use constantly.

Adding and removing

python
fruits = ["mango", "banana"]
fruits.append("guava")
fruits.insert(0, "apple")
print(fruits)

fruits.remove("banana")
last = fruits.pop()
print(last, fruits)
print(len(fruits), "mango" in fruits)
Output
['apple', 'mango', 'banana', 'guava']
guava ['apple', 'mango']
2 True
  • append(x) adds to the end; insert(i, x) adds at position i.
  • extend(other) adds every item of another list.
  • remove(x) deletes the first x; pop() removes and returns the last item, pop(i) the one at i.
  • index(x) finds x's position; count(x) counts it; clear() empties the list.

Sorting

python
marks = [72, 45, 91, 60]
print(sorted(marks))
print(marks)
marks.sort(reverse=True)
print(marks)
print(max(marks), min(marks), sum(marks))

names = ["meena", "Arun", "bala", "Zara"]
print(sorted(names))
print(sorted(names, key=str.lower))
Output
[45, 60, 72, 91]
[72, 45, 91, 60]
[91, 72, 60, 45]
91 45 268
['Arun', 'Zara', 'bala', 'meena']
['Arun', 'bala', 'meena', 'Zara']

sorted(x) gives back a new sorted list and leaves the original alone. x.sort() sorts the list itself and returns None. Capital letters sort before small ones, which is why key=str.lower is needed to sort names the way people expect.

Warning

marks = marks.sort() is a classic mistake: sort() returns None, so marks is now None and the list is lost. Either call marks.sort() on its own line, or write marks = sorted(marks).

Copying a list

python
a = [1, 2, 3]
b = a
c = a.copy()
a.append(4)
print(b)
print(c)
Output
[1, 2, 3, 4]
[1, 2, 3]

b = a does not copy anything — it gives the same list a second name, so a change through one name shows through the other. a.copy() (or a[:]) makes a real, separate list.

After x = [3, 1, 2] and y = sorted(x), what is x?

Try this now

  1. Keep asking for marks until the user types "done", then print the highest, lowest and average.
  2. Remove every duplicate from a list while keeping the original order (hint: build a new list, checking "not in").

Create a free account to save your progress, or sign in.