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
Community
  • 1
  • 1
Markum
  • 3,919
  • 8
  • 26
  • 30
  • 2
    possible duplicate of [for x in y, type iteration in python. Can I find out what iteration I'm currently on?](http://stackoverflow.com/questions/2894323/for-x-in-y-type-iteration-in-python-can-i-find-out-what-iteration-im-currentl) and [Iteration count in python?](http://stackoverflow.com/questions/8590810/iteration-count-in-python) and [Identify which iteration you are on in a loop in python](http://stackoverflow.com/questions/4751092/identify-which-iteration-you-are-on-in-a-loop-in-python). – Felix Kling Jun 02 '12 at 22:29

2 Answers2

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.

Levon
  • 138,105
  • 33
  • 200
  • 191
0

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

i = 0
for fruit in fruits:
    i += 1
    print i, fruit.capitalize()
matt b
  • 138,234
  • 66
  • 282
  • 345
  • 2
    Why do it manually in an uglier way? -1. Don't reinvent the wheel. – Gareth Latty Jun 02 '12 at 22:55
  • 1
    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 – matt b Jun 02 '12 at 23:52