Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I enumerate() over a list of tuples in Python?

I've got some code like this:

letters = [('a', 'A'), ('b', 'B')] i = 0 for (lowercase, uppercase) in letters:     print "Letter #%d is %s/%s" % (i, lowercase, uppercase)     i += 1 

I've been told that there's an enumerate() function that can take care of the "i" variable for me:

for i, l in enumerate(['a', 'b', 'c']):     print "%d: %s" % (i, l) 

However, I can't figure out how to combine the two: How do I use enumerate when the list in question is made of tuples? Do i have to do this?

letters = [('a', 'A'), ('b', 'B')] for i, tuple in enumerate(letters):     (lowercase, uppercase) = tuple     print "Letter #%d is %s/%s" % (i, lowercase, uppercase) 

Or is there a more elegant way?

like image 464
mike Avatar asked May 11 '09 18:05

mike


People also ask

Does enumerate work on tuples?

Enumerate can be used to loop over a list, tuple, dictionary, and string.

How do you iterate a list of tuples?

Easiest way is to employ two nested for loops. Outer loop fetches each tuple and inner loop traverses each item from the tuple. Inner print() function end=' ' to print all items in a tuple in one line.

Can you use enumerate with a list in Python?

Enumerate() in Python Enumerate() method adds a counter to an iterable and returns it in a form of enumerating object. This enumerated object can then be used directly for loops or converted into a list of tuples using the list() method.

How do you iterate over a tuple in Python?

You can loop through the tuple items by using a for loop.


2 Answers

This is a neat way to do it:

letters = [('a', 'A'), ('b', 'B')] for i, (lowercase, uppercase) in enumerate(letters):     print "Letter #%d is %s/%s" % (i, lowercase, uppercase) 
like image 169
RichieHindle Avatar answered Sep 20 '22 14:09

RichieHindle


This is how I'd do it:

import itertools  letters = [('a', 'A'), ('b', 'B')] for i, lower, upper in zip(itertools.count(),*zip(*letters)):     print "Letter #%d is %s/%s" % (i, lower, upper) 

EDIT: unpacking becomes redundant. This is a more compact way, which might work or not depending on your use case:

import itertools  letters = [('a', 'A'), ('b', 'B')] for i in zip(itertools.count(),*zip(*letters)):     print "Letter #%d is %s/%s" % i 
like image 29
Algorias Avatar answered Sep 20 '22 14:09

Algorias