1

Possible Duplicate:
for x in y, type iteration in python. Can I find out what iteration I'm currently on?
Iteration count in python?

Kind of hard to explain, but when I run something like this:

fruits = ['apple', 'orange', 'banana', 'strawberry', 'kiwi']

for fruit in fruits:
    print fruit.capitalize()

It gives me this, as expected:

Apple
Orange
Banana
Strawberry
Kiwi

How would I edit that code so that it would "count" the amount of times it's performing the for, and print this?

1 Apple
2 Orange
3 Banana
4 Strawberry
5 Kiwi
1

2 Answers 2

6
for i,fruit in enumerate(fruits, 1):
    print i, fruit.capitalize()

will do what you want and print:

1 Apple
2 Orange
3 Banana
4 Strawberry
5 Kiwi

By default enumerate() will start generating an index with 0 if not specified, but you can specify the starting value as shown.

Sign up to request clarification or add additional context in comments.

Comments

0

Ignoring enumerate(iterable), you could just count yourself:

i = 0
for fruit in fruits:
    i += 1
    print i, fruit.capitalize()

2 Comments

Why do it manually in an uglier way? -1. Don't reinvent the wheel.
I wasn't suggesting this was a good way, but I wanted to point out to the OP how you could simply modify the existing code to accomplish what he wants - that it isn't a huge leap from what he had to what he wants, and to show what enumerate is essentially doing for you. But I guess we downvote less-than-optimal answers these days

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.