Nested lists in python

3

I need a help, let's say I have the following list:

lista = [1,2,3,4,5,[6,7,8,9],10,11,12,13,14,15]

If I want to print each of the items in this list I would do one:

for i in lista:
   print(lista)

So far so good. However, I wanted to know how I can do the same for the list that is in the list.

I thought the following code, however, is not working:

   for i in lista:
      for i in lista:
          print(i)

Can anyone help me with this problem?

    
asked by anonymous 07.03.2018 / 14:33

2 answers

3

Can solve using recursion. It creates a function to print the list, and whenever each element of that list is another list it returns to call the same function on that element.

To find out if an element is a list you can use the isinstance function by passing as second argument list .

Example:

def imprimir_lista(lista):
    for elemento in lista:
        if isinstance(elemento, list): # se este elemento é uma lista, chama a mesma funçao
            imprimir_lista(elemento)
        else: # caso contrário imprime normalmente
            print(elemento)

Output:

>>> lista = [1,2,3,4,5,[6,7,8,9],10,11,12,13,14,15]
>>> imprimir_lista(lista)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

See another example with an even more nested list:

>>> lista = [1,2,[3,4,[5,6]]]
>>> imprimir_lista(lista)
1
2
3
4
5
6

View the code to run on Ideone

    
07.03.2018 / 14:56
2

First, your i variable is being overwritten, you should use another variable, in addition to you iterating back in the original list, when it should iterate over var i only when it is a list . The second for should only be done if the element of the original list is of type list, see the example below:

lista = [1,2,3,4,5,[6,7,8,9],10,11,12,13,14,15]

for elemento in lista:
    if isinstance(elemento, list):
        for subelemento in elemento:
            print(subelemento)
    else:
        print(elemento)

The isinstance () function checks whether the element is a list to do so, otherwise it prints the element normally.

    
07.03.2018 / 14:59