Joost
Joost

Reputation: 4134

iterate over list of tuples in two notations

I'm iterating over a list of tuples, and was just wondering if there is a smaller notation to do the following:

for tuple in list:
    (a,b,c,d,e) = tuple

or the equivalent

for (a,b,c,d,e) in list:
    tuple = (a,b,c,d,e)

Both of these snippits allow me to access the tuple per item as well as as a whole. But is there a notation that somehow combines the two lines into the for-statement? It seems like such a Pythonesque feature that I figured it might exist in some shape or form.

Upvotes: 0

Views: 219

Answers (3)

David Z
David Z

Reputation: 131640

There isn't anything really built into Python that lets you do this, because the vast majority of the time, you only need to access the tuple one way or the other: either as a tuple or as separate elements. In any case, something like

for t in the_list:
    a,b,c,d,e = t

seems pretty clean, and I can't imagine there'd be any good reason to want it more condensed than that. That's what I do on the rare occasions that I need this sort of access.

If you just need to get at one or two elements of the tuple, say perhaps c and e only, and you don't need to use them repeatedly, you can access them as t[2] and t[4]. That reduces the number of variables in your code, which might make it a bit more readable.

Upvotes: 0

Sukrit Kalra
Sukrit Kalra

Reputation: 34523

This might be a hack that you could use. There might be a better way, but that's why it's a hack. Your examples are all fine and that's how I would certainly do it.

>>> list1 = [(1, 2, 3, 4, 5)]
>>> for (a, b, c, d, e), tup in zip(list1, list1):
       print a, b, c, d, e
       print tup

1 2 3 4 5
(1, 2, 3, 4, 5)

Also, please don't use tuple as a variable name.

Upvotes: 2

jamylak
jamylak

Reputation: 133634

The pythonic way is the first option you menioned:

for tup in list:
    a,b,c,d,e = tup

Upvotes: 2

Related Questions