Home tuple unpacking in python using for loops?
Reply: 1

tuple unpacking in python using for loops?

harshul1
1#
harshul1 Published in 2018-02-14 00:44:13Z
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!

Ray
2#
Ray Reply to 2018-02-14 01:03:22Z

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)
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.32302 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO