25. lists

A list is a set of data ordered in sequence. Lists are constructed by enclosing multiple items separated by commas in [ ] brackets:

>>> lista_impares = [1, 3, 5, 7, 9]
>>> lista_nombres = ['Juan', 'Nerea', 'Camila', 'Joaquín']
>>> lista_booleana = [True, False, False, True]

As can be seen, the data in a list can be of any type. You can even make lists with multiple data types or a list of lists:

>>> nombre_y_altura = [ ['Juan', 176], ['Nerea', 169], ['Camila', 166] ]

Lists are a very versatile tool for storing and working with program data.

multiline lists

Lists with many elements or with a complex structure can be written by separating the elements on consecutive lines to make the result more readable:

lista = [
    ['Juan', 176],
    ['Nerea', 169],
    ['Camila', 166]
    ]

lista = [
   'Primer texto',
   'Segundo texto',
   'Último texto'
   ]

Operations with lists

Lists can be added and multiplied by a number, just like strings:

>>> [1, 2, 3] + [4, 5, 6]
    [1, 2, 3, 4, 5, 6]

>>> [1, 2] * 5
    [1, 2, 1, 2, 1, 2, 1, 2, 1, 2]

in statement

The in statement returns a True or False value and allows to know if a data is inside a list:

>>> lista = [1, 2, 3, 'a', 'b', 'c']
>>> 3 in lista
    True

>>> 'b' in lista
    True

>>> 10 in lista
    False

>>> 'x' in lista
    False

The not in statement is the opposite of the in statement and returns true if an element is not in a list:

>>> 'x' not in lista
    True

>>> 3 not in lista
    False

Exercises

  1. Write a program that assigns the names of five classmates or friends to a list.

  2. Add to the previous program another list with the ages of the previous people. If you do not know them, you can write them approximately.

    Create a third list containing the two previous lists:

    [ ['nombre1', 'nombre2', ....], [edad1, edad2, ...] ]
    
  3. Write a program that creates a multi-line list with three famous phrases that you choose from this web page or another web of your choice.

  4. Write a list with the first 10 prime numbers. You can find what they are in an Internet search engine.

    Make the list in two parts. First you define the list with 5 primes and then you add 5 more primes to the list.

  5. Modify the above program so that it checks if the numbers 3, 7, 9, 13, and 20 belong to the first 10 prime numbers.

    To do this you must define a function that checks if the number is in the list and prints the result.

    Call the function 5 times to check all 5 numbers.