Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Unpacking an inner nested tuple/list while still getting its index number

I am familiar with using enumerate():

>>> seq_flat = ('A', 'B', 'C') >>> for num, entry in enumerate(seq_flat):         print num, entry 0 A 1 B 2 C 

I want to be able to do the same for a nested list:

>>> seq_nested = (('A', 'Apple'), ('B', 'Boat'), ('C', 'Cat')) 

I can unpack it with:

>>> for letter, word in seq_nested:         print letter, word A Apple B Boat C Cat 

How should I unpack it to get the following?

0 A Apple 1 B Boat 2 C Cat 

The only way I know is to use a counter/incrementor, which is un-Pythonic as far as I know. Is there a more elegant way to do it?

like image 487
Kit Avatar asked Jul 26 '10 00:07

Kit


People also ask

Is unpacking possible in a tuple?

In python tuples can be unpacked using a function in function tuple is passed and in function, values are unpacked into a normal variable. The following code explains how to deal with an arbitrary number of arguments. “*_” is used to specify the arbitrary number of arguments in the tuple.

Does tuple unpacking work with lists?

Unpack a nested tuple and list. You can also unpack a nested tuple or list. If you want to expand the inner element, enclose the variable with () or [] .

How do I unpack a list of tuples in Python?

Python uses the commas ( , ) to define a tuple, not parentheses. Unpacking tuples means assigning individual elements of a tuple to multiple variables. Use the * operator to assign remaining elements of an unpacking assignment into a list and assign it to a variable.

How does tuple unpacking work in Python?

Unpacking Tuples When we put tuples on both sides of an assignment operator, a tuple unpacking operation takes place. The values on the right are assigned to the variables on the left according to their relative position in each tuple . As you can see in the above example, a will be 1 , b will be 2 , and c will be 3 .


1 Answers

for i, (letter, word) in enumerate(seq_nested):   print i, letter, word 
like image 178
Alex Martelli Avatar answered Sep 27 '22 16:09

Alex Martelli