Browse 2D list in Python

Asked

Viewed 418 times

1

I have the code below and I want to go through and display item by item from that list. However, I cannot do this because the entire list is displayed. I ask for your help.

lista = [[10,20,30,40],[50,60,70,80]]
i = 0
for i in range(2):
    print (lista[i])

2 answers

3

Cycle is inside the other (nested):

for sublista in lista:
    for item in sublista:
        print item

Or if you don’t need to do anything to the sublists you can just make the list flat:

 print '\n'.join(str(item) for sub in lista for item in sub) 
  • Thanks friend! It worked perfectly.

  • Danilo, if the answer helped you, consider mark her as accepted.

  • @Danilo. Glad I could help

  • Certainly, I will do it. But inform that I can only do it after 10 minutes. That’s why it hasn’t appeared to you yet.

  • 1

    Obgado @Luizvieira (:

0


You can display all items of a sublist in a single row, i.e., use a row to display all items of a sublist. For this you can use the following algorithm...

lista = [[10, 20, 30, 40], [50, 60, 70, 80]]

cont = 0
for sublista in lista:
    cont += 1
    print(f'\033[32mOs elementos da {cont}ª sublista são: ')
    for item in sublista:
        print(item, end='')
        print(', ' if item < sublista[-1] else '.', end='')
    print()

See how the algorithm works on repl it..

Browser other questions tagged

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