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?
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.
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 [] .
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.
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 .
for i, (letter, word) in enumerate(seq_nested): print i, letter, word
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With