# 27. list iteration¶

Iterating a list means going through each of the elements in the list one by one to perform some action on each element. This technique allows you to manipulate data repetitively without having to write the code multiple times.

Lists can be iterated with a for loop.

Example:

lista = ['Juan', 'Nerea', 'Camila', 'Esteban']
for nombre in lista:
print(f'Hola {nombre}')

Exit:

Hola Juan
Hola Nerea
Hola Camila
Hola Esteban

## len() function¶

The len() function returns the number of elements that a list contains. This is useful for iterating over the index that each element is at:

>>> lista = ['A', 'B', 'C', 'D', 'E', 'F']
>>> len(lista)
6

>>> for i in range(len(lista)):
...     if i % 2 == 0:
...         print(f'{lista[i]}')
...
A
C
E

>>> for i in range(len(lista)):
...     if i % 2 != 0:
...         print(f'{lista[i]}')
...
B
D
F

## list() function¶

The list() function allows you to create a list from multiple elements or convert an iterable like range() to a list:

>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> list(range(1, 11, 2)) # Impares
[1, 3, 5, 7, 9]

>>> list('Hola, mundo')
['H', 'o', 'l', 'a', ',', ' ', 'm', 'u', 'n', 'd', 'o']

## list comprehension¶

List comprehension is a short and fast method of generating lists. Use the for loop inside two [ ] brackets

Example:

lista = [num for num in range(10)]

It is equivalent to this other code, slower and longer to write:

lista = []
for num in range(10):
lista.append(num)

## Exercises¶

1. Write a program that defines a list of names and then prints the name and the letter it starts with on the screen in the following format:

Juan       comienza por 'J'
Nerea      comienza por 'N'
Camila     comienza por 'C'
Esteban    comienza por 'E'

2. Write a program that requests a phrase for keyboard input. The program must convert the phrase to a list of characters.

The program should then print the sentence backwards, starting with the last letter and ending with the first letter.

Hint: To go from end to beginning, you can use an index with the range(len(list), -1, -1) function.

3. Write a program that generates a list of odd numbers up to 99. The program should add all the numbers in the list and print the result, which should equal 2500.

4. Write a program that defines the following list of elements:

lista_1 = [1, 2, 2, 3, 4, 4, 5, 5, 5, 7]

The program should generate a new list that contains all the elements of the first one except those that are duplicates:

lista_2 = [1, 2, 3, 4, 5, 7]

Hint: loop through all the elements in list_1 and if they are not in list_2, add them to list_2.

5. Write a program that reads a sentence from the keyboard and encrypts it with the following algorithm.

The program must split the phrase into letters with the list(phrase) function.

Next the program should generate a new list with the letters with even index.

The letters with odd index must be added to this new list at the end.

Finally all the letters of the new list will be printed together.

Exit:

Introduce una frase: La lluvia en Sevilla es una pura maravilla

L lvae eil suapr aailalui nSvlae n uamrvla

Exit:

Introduce una frase: En un lugar de la Mancha, de cuyo nombre no quiero acordarme

E nlgrd aMnh,d uonmr oqir cramnu ua el aca ecy oben ueoaodre

Exit:

Introduce una frase: Si eres capaz de descifrar esto, es que eres un/a crack

S rscpzd ecfa so sqeee nacakiee aa edsirret,e u rsu/ rc

6. Write a program that breaks the code produced by the above program.

Clue:

frase = input('Escribe la frase cifrada: ')

# Para evitar errores debe haber un número par de caracteres
if len(frase) % 2 != 0:
frase = frase + ' '

# Genera dos listas con los caracteres de índice par
# y los caracteres de índice impar