Vinay Garg Assistant Professor

Lesson 17: Lists: the workhorse collection

A list holds many values in order and lets you change them. Append, insert, remove, pop and sort are the five methods that cover most work with lists.

A dark code window showing a list of fruits with items added and removed

In short

  • A list is written with square brackets and keeps its order: `["apple", "banana"]`.
  • Lists are mutable, so `append()`, `insert()`, `remove()` and `sort()` change the list in place.
  • `pop()` removes and returns an item; `remove()` removes the first matching value and returns nothing.
  • `sort()` changes the list, `sorted()` returns a new one — the same split applies to `reverse()`.

0

fixed size: a list grows as needed

Python docs

2

sorting options: sort() in place, sorted() a copy

Python docs

What a list is

A list is an ordered collection that can hold any values and can change after it is created. Square brackets create one, and commas separate the items.

fruits = ["apple", "banana", "cherry"]
marks = [45, 67, 89]
mixed = ["Asha", 21, True]

print(fruits)
print(marks)
print(mixed)

The program

# lists.py — the five methods that do most of the work

fruits = ["apple", "banana", "cherry"]
print(fruits[0], fruits[-1])      # apple cherry
print(fruits[1:])                 # ['banana', 'cherry']

fruits.append("date")             # adds at the end
fruits.insert(1, "blueberry")     # adds at position 1
print(fruits)

print(fruits.pop())               # date, removed and returned
fruits.remove("banana")           # removed by value
print(fruits)

numbers = [5, 2, 9, 1]
numbers.sort()
print(numbers)                    # [1, 2, 5, 9]
numbers.sort(reverse=True)
print(numbers)                    # [9, 5, 2, 1]
print(len(numbers), 9 in numbers) # 4 True

How it works, step by step

  1. fruits[0] is the first item, fruits[-1] the last. Negative indexes count backwards.
  2. fruits[1:] slices from position 1 to the end.
  3. append() adds one item to the end. insert(1, x) puts it at position 1 and shifts the rest along.
  4. pop() without an argument removes the last item and returns it, so you can store it.
  5. remove(value) finds the first matching item and deletes it. It returns None, and raises ValueError if the value is absent.
  6. sort() arranges the list in place, smallest first. reverse=True flips the order.

What it prints

apple cherry
['banana', 'cherry']
['apple', 'blueberry', 'banana', 'cherry', 'date']
date
['apple', 'blueberry', 'cherry']
[1, 2, 5, 9]
[9, 5, 2, 1]
4 True

The methods, side by side

MethodEffectReturns
append(x)Adds x at the endNone
insert(i, x)Adds x at position iNone
extend(list)Adds every item of another listNone
remove(x)Deletes the first xNone
pop(i)Deletes the item at i and returns itthe item
sort()Sorts in placeNone
reverse()Reverses in placeNone
count(x), index(x)Counts or finds xa number

Common mistakes

  • numbers = numbers.sort() sets numbers to None, because sort returns nothing. Call sort() on its own line.
  • Copying with b = a and then changing b, which also changes a. Both names point at one list; use a.copy() or a[:].
  • Removing items while looping over the same list. Loop over a copy.

Practice

Try these before moving on. Each one uses only what this lesson covered.

  1. Create a list of five subjects, add one at the end and one at position 1, then print the list.
  2. Remove one subject by value and one by position, and print what each call returned.
  3. Sort a list of marks in ascending and descending order and print both.
  4. Find the second largest number in a list of numbers.

Sources

Frequently asked questions

How do I add an item to a list in Python?

append(x) adds it at the end, insert(i, x) puts it at a position, and extend(other) adds everything from another list. All three change the list in place and return None.

What is the difference between remove() and pop()?

remove(value) deletes the first item with that value and returns nothing. pop(index) deletes the item at a position and returns it, which is useful when you need the value.

What is the difference between sort() and sorted()?

sort() rearranges the list itself and returns None. sorted(list) leaves the original untouched and returns a new sorted list.

How do I copy a list properly?

Use list.copy(), list[:] or list(list). A plain b = a only copies the reference, so a change through one name shows up in the other.

Vinay Garg

Vinay Garg

Assistant Professor of Computer Science at Multani Mal Modi College, Patiala. Twenty-five years of teaching web programming, and a habit of building the things I teach about.