26. list indices

To get and manage the data in a list, you can use indices and slices just like you used with strings:

>>> lista = ['a', 'b', 'c', 'd', 'e']
>>> lista[0]
    'a'
>>> lista[3]
    'd'
>>> lista[-1]
    'e'

This schematic can help to understand the position of the indices:

[ 'a', 'b', 'c', 'd', 'e' ]
 ^    ^    ^    ^    ^   ^
 0    1    2    3    4   5
-5   -4   -3   -2   -1

Indices in brackets return the element at that position in the list, starting at the first position at index zero.

slices

On the other hand, the slices return another list composed of the elements that are between two indices:

>>> lista[0:1]
    ['a']

>>> lista[1:-1]
    ['b', 'c', 'd']

>>> lista[10:20]   # Índices fuera de rango devuelven una lista vacía
    []

>>> lista[:3]
    ['a', 'b', 'c']

>>> lista[3:]
    ['d', 'e']

Modification of elements

Unlike with text strings, in lists you can modify their elements by changing them to another value:

>>> lista = ['a', 'b', 'c', 'd', 'e']

>>> # Cambia el primer elemento de la lista
>>> lista[0] = 'A'
>>> lista
    ['A', 'b', 'c', 'd', 'e']

>>> # Cambia los elementos 3º y 4º de la lista por otra lista
>>> lista[2:4] = ['=', 'X']
    ['A', 'b', '=', 'X', 'e']

Sentence of

The statement del (word that comes from delete) removes an element from the list that is in a certain position:

>>> lista = [1, 2, 3, 4, 5, 6]
>>> del lista[0]
>>> lista
    [2, 3, 4, 5, 6]

>>> del lista[2]
>>> lista
    [2, 3, 5, 6]

You can also use slices with the del:: statement

>>> lista = [1, 2, 3, 4, 5, 6]
>>> del lista[1:3]
>>> lista
    [1, 4, 5, 6]

Exercises

  1. Write a program that defines a list with the first 10 prime numbers. Next you need to print the first, third, and seventh prime numbers.

  2. Modify the above program so that it prints the sum of the first 4 prime numbers. You must program a loop that counts from 0 to 3 and use these numbers as indices to retrieve the prime numbers from the list.

  3. Write a program that defines a list with three names. The program should print the list, modify the second name, and reprint the modified list.

  4. Write a program that defines a list with the first 6 letters of the alphabet in uppercase.

    Prints a sublist from 'B' to 'D'.

    Prints a sublist from 'C' to the end.

  5. Modify the above program so that it deletes the even positions from the list and then prints the resulting list:

    ['A', 'C', 'E']
    

    Note that as items are removed from the list, subsequent items change position.

  6. Write a program that defines a list with the first 6 letters of the alphabet in uppercase. Then a for loop should change each letter to its lowercase value thanks to the .lower()` method.

    The for loop must measure the length of the list with the len() function.

    Clue:

    lista = ['A', ... ]
    for i in range( ... ):
        lista[i] = ...
    print(lista)