0

See the following code :

choices = ['pizza', 'pasta', 'salad', 'nachos']
print 'Your choices are:'
for index, item in enumerate(choices):
    print index+1, item

Output:

Your choices are:
1 pizza
2 pasta
3 salad
4 nachos
None

In the third line, for takes two arguments.

for index, item in enumerate(choices):

But the syntax of for loop is:

array=[...]
for element in array

How does this actually work? Does for loop take in multiple arguments? If yes, how can we use them?

3

3 Answers 3

5

Python lets you unpack sequences on assignment:

>>> foo = ('spam', 'ham')
>>> bar, baz = foo
>>> bar
'spam'
>>> baz
'ham'

The same can be done in a for loop:

list_of_tuples = [('foo', 'bar'), ('spam', 'ham')]
for value1, value2 in list_of_tuples:
    print value1, value2

would print

foo bar
spam ham

The enumerate() function produces tuples of two values, the index, and value from the sequence passed in as an argument:

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
Sign up to request clarification or add additional context in comments.

Comments

0

Actually, it takes one argument, of type tuple, which is then unpacked.

The syntax is similar to the following:

a, b = b, a

which is a nice way of writing a "swap" of the two variables.

However, think of it as

(a,b) = (b,a)

Then you have a "single tuple" assignment, combined with tuple unpacking.

Comments

0

It's tuple unpacking. In an assignment, you can put a tuple of variables on the left side and if the right side has exactly that amount of elements, they get assigned like that:

a, b = (3, 4)  # Now a is 3 and b is 4

You can do that in for loops as well

for a, b in [(3, 4), (5, 6)]:
    print(a)

will print 3 and then 5.

Since enumerate yields tuples of (index, element), the for loop in your element works.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.