Skip to content

    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:

    basico/cap19_listas.pylinhas 10 a 13
    frutas = ["maçã", "banana", "manga"]
    print(frutas[0], frutas[-1], frutas[0:2])
    frutas[1] = "uva"
    print(frutas)
    
    Output
    maçã manga ['maçã', 'banana']
    ['maçã', 'uva', 'manga']
    

    Main methods

    basico/cap19_listas.pylinhas 18 a 26
    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))
    
    Output
    [0, 3, 1, 4, 1, 5, 9, 2, 6]
    [0, 3, 4, 1, 5, 9, 2] 6
    2 1
    
    MethodWhat it doesReturns
    append(x)Adds to the endNone
    extend(iteravel)Adds multiple items to the endNone
    insert(i, x)Inserts at position iNone
    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 placeNone
    reverse()Reverses in placeNone

    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:

    basico/cap19_listas.pylinhas 28 a 34
    valores = [3, 1, 2]
    print(sorted(valores))
    print(valores)
    resultado = valores.sort()
    print(resultado, valores)
    valores.sort(reverse=True)
    print(valores)
    
    Output
    [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:

    basico/cap19_listas.pylinhas 39 a 45
    a = [1, 2, 3]
    b = a
    b.append(4)
    print(a)
    c = a.copy()
    c.append(5)
    print(a, c)
    
    Output
    [1, 2, 3, 4]
    [1, 2, 3, 4] [1, 2, 3, 4, 5]
    
    basico/cap19_listas.pylinhas 47 a 55
    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)
    
    Output
    [[99, 2], [3, 4]]
    [[99, 2], [3, 4]] [[0, 2], [3, 4]]
    

    Useful operations

    basico/cap19_listas.pylinhas 60 a 68
    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)
    
    Output
    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:

    basico/cap19_listas.pylinhas 73 a 82
    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))
    
    Output
    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.