xhhg3
xhhg3

Reputation: 13

Itirating through list of tuples with nested for loops

I have a list containing tuples. Each tuple holds 2 elements. I tried to print it with the following code, but it gives the error message:

TypeError: list indices must be integers or slices, not tuple

Relevant code:

for i in list:
    for j in [1, 2]:
        print(list[i][j])

With the idea of printing each element of the 1st tuple, each element of the 2nd tuple etc

Upvotes: 1

Views: 2000

Answers (3)

Miraj50
Miraj50

Reputation: 4407

Realise i in the loop is actually a tuple (an element of a list). So, you just need to print element of i like i[j]. list[i] makes no sense as i should be an integer, but it is actually an element of the list, that is a tuple. You must also be getting an error like this TypeError: list indices must be integers, not tuple. Well I am. So that should be a hint/explanation to you.

lst = [(1,2),(5,9)]
for i in lst:
    for j in [0, 1]:
        print(i[j])
    print

Output:

1 2
5 9

Upvotes: 4

progmatico
progmatico

Reputation: 4964

You can unpack the tuple in the for loop

>>> tup_list = [(1,2), (3,4)]
>>> for a,b in tup_list:
...     print(a,b)
... 
1 2
3 4

Upvotes: 2

Serg Anuke
Serg Anuke

Reputation: 168

You can use nested list comprehension:

[i for subset in list for i in subset] give you flat list

It's more pythonic!

Upvotes: 0

Related Questions