Nested lists in python

Asked

Viewed 1,627 times

5

I need some 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 wanted to print each of the items on that list I would make one:

for i in lista:
   print(lista)

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

I thought of the following code, however,:

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

Can someone help me with this problem ?

3 answers

5


You can solve it using recursion. Creates a function to print the list, and whenever each element in that list is another list calls back the same function on that element.

To know if an element is a list you can use the function isinstance 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)

Exit:

>>> 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

See the code to run on Ideone

3

First, your variable is i is being overwritten, should use another variable, besides you iterate again in the original list, when should iterate on var i only when it is a list. The second for should only be done if the original list element is of the list type, 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 if the element is a list to loop, otherwise prints the element normally.

1

If you want to print individually the elements of a simple irregular sequence, a sequence formed of regular sequences, one option is to flatten this sequence to print individually the elements in the way that suits you.

To flatten a single irregular sequence, the class method can be used chain.from_iterable() which is used to chain the elements of an eternal consisting of eternal.

As argument is passed to chain.from_iterable() a list comprehension that traverses a sequence checking whether each element also a sequence. If the element is a sequence just copy it, or convert it to tuple itself resulting in a list of sequences:

from itertools import chain
from collections.abc import Sequence

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

l = chain.from_iterable([e if isinstance(e, Sequence) else (e,) for e in lista])

print(*l, sep="\n")

In the case of a composite irregular sequence, a sequence formed of regular and irregular sequences, a recursive algorithm similar to the previous one is used that when it comes across a previously nested sequence it flattens:

from itertools import chain
from collections.abc import Sequence

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

def achatar(l):
  return chain.from_iterable([achatar(e) if isinstance(e, Sequence) else (e,) for e in l])

l= achatar(lista)

print(*l, sep="\n")

Algorithm that can converted to a lambda expression:

from itertools import chain
from collections.abc import Sequence

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

(achatar:= lambda l: chain.from_iterable([achatar(e) if isinstance(e, Sequence) else (e,) for e in l]))

l= achatar(lista)

print(*l, sep="\n")

Test the algorithms in Repl.it

Browser other questions tagged

You are not signed in. Login or sign up in order to post.