Chapter 19, Basic
Lists
The list is the data structure you will use the most. Understanding what is mutable in it avoids the hardest bugs to find.
Code for this chapter: basico/cap19_listas.py
Create, access, and slice
A list is an ordered and mutable sequence of items of any type. The indices and slices work like in strings, but here you can change the items:
frutas = ["maçã", "banana", "manga"]
print(frutas[0], frutas[-1], frutas[0:2])
frutas[1] = "uva"
print(frutas)
maçã manga ['maçã', 'banana']
['maçã', 'uva', 'manga']
Main methods
numeros = [3, 1, 4, 1, 5]
numeros.append(9)
numeros.insert(0, 0)
numeros.extend([2, 6])
print(numeros)
numeros.remove(1)
ultimo = numeros.pop()
print(numeros, ultimo)
print(numeros.index(4), numeros.count(1))
[0, 3, 1, 4, 1, 5, 9, 2, 6]
[0, 3, 4, 1, 5, 9, 2] 6
2 1
| Method | What it does | Returns |
|---|---|---|
append(x) | Adds to the end | None |
extend(iteravel) | Adds multiple items to the end | None |
insert(i, x) | Inserts at position i | None |
remove(x) | Removes the first occurrence (or ValueError) | None |
pop(i) | Removes and returns the item (the last one, by default) | The item |
sort() | Sorts in place | None |
reverse() | Reverses in place | None |
Almost all methods that alter the list return None. The classic mistake is to write lista = lista.sort() and end up with None. Compare with sorted(), which returns a new list and does not modify the original:
valores = [3, 1, 2]
print(sorted(valores))
print(valores)
resultado = valores.sort()
print(resultado, valores)
valores.sort(reverse=True)
print(valores)
[1, 2, 3]
[3, 1, 2]
None [1, 2, 3]
[3, 2, 1]
Assignment is not copying
b = a does not create a new list: it creates a second name for the same list. To copy, use copy(). And the copy is shallow: the internal items remain shared. For lists within lists, it is necessary to copy.deepcopy:
a = [1, 2, 3]
b = a
b.append(4)
print(a)
c = a.copy()
c.append(5)
print(a, c)
[1, 2, 3, 4]
[1, 2, 3, 4] [1, 2, 3, 4, 5]
import copy
matriz = [[1, 2], [3, 4]]
rasa = matriz.copy()
rasa[0][0] = 99
print(matriz)
profunda = copy.deepcopy(matriz)
profunda[0][0] = 0
print(matriz, profunda)
[[99, 2], [3, 4]]
[[99, 2], [3, 4]] [[0, 2], [3, 4]]
Useful operations
n = [4, 8, 2, 9]
print(len(n), min(n), max(n), sum(n))
print(n + [1], n * 2)
print(8 in n)
print(list(reversed(n)))
del n[0]
print(n)
n[1:3] = [0, 0, 0]
print(n)
4 2 9 23
[4, 8, 2, 9, 1] [4, 8, 2, 9, 4, 8, 2, 9]
True
[9, 2, 8, 4]
[8, 2, 9]
[8, 0, 0, 0]
Stack and queue
A list works well as a stack (last in, first out), with append and pop at the end, which are fast. As queue, it is bad: pop(0) needs to shift all items. For queues, use collections.deque:
from collections import deque
pilha = []
pilha.append("a")
pilha.append("b")
print(pilha.pop())
fila = deque(["x", "y", "z"])
fila.append("w")
print(fila.popleft(), list(fila))
b
x ['y', 'z', 'w']
Exercise 1
Second largest
Write segundo_maior(numeros) that ignores repetitions. For [5, 5, 3] the result is 3. The next chapter presents the set, which helps here.
Exercise 2
Is the list sorted?
Write esta_ordenada(numeros) without using sort() in the original list.