harshul1
harshul1

Reputation: 13

tuple unpacking in python using for loops?

l=[(1,2),(3,4),(5,6)]
for (a,b) in list:
    for i in range(len(list)):
        if i%2==0:
            print(b)
            break
        else:
            print(a)
            break

output-
2
4
6

expected output-
1
4
5



PLEASE correct it!

Upvotes: 0

Views: 529

Answers (1)

Ray
Ray

Reputation: 176

You may want to be more specific about what you want to achieve. Based on your "expected output", I assume you want the 1st element when the index is even and the 2nd element when the index is odd.

l=[(1,2),(3,4),(5,6)]
for idx, (x, y) in enumerate(l):
  val = x if idx%2==0 else y
  print(val)

Upvotes: 1

Related Questions