Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to unpack a tuple while using enumerate in loop?

Tags:

python

Consider this:

the_data = ['a','b','c']

With enumerate this loop can be written as:

  for index,item in enumerate(the_data):
     # index = 1 , item = 'a'

If the_data = { 'john':'football','mary':'snooker','dhruv':'hockey'}

Loop with key value pair assigned in loop:

for name,sport in the_data.iteritems():
 #name -> john,sport-> football

While using enumerate, the data becomes a tuple within the loop, hence needs one extra line of assignment after the loop declaration :

#can assignment of name & sport happen within the `for-in` line itself ?
 for index,name_sport_tuple in enumerate(the_data.iteritems()):
         name,sport = name_sport_tuple  # Can this line somehow be avoided ?
         #index-> 1,name-> john, sport -> football 
like image 925
DhruvPathak Avatar asked Feb 03 '14 14:02

DhruvPathak


1 Answers

Use this:

for index, (name, sport) in enumerate(the_data.iteritems()):
   pass

This is equivalent to:

>>> a, (b, c) = [1, (2, 3)]
>>> a, b, c
(1, 2, 3)

This is commonly used with zip and enumerate combo as well:

for i, (a, b) in enumerate(zip(seq1, seq2)):
    pass
like image 123
Ashwini Chaudhary Avatar answered Oct 14 '22 06:10

Ashwini Chaudhary