12

I've got the following code:

hey = ["lol", "hey", "water", "pepsi", "jam"]

for item in hey:
    print(item)

Do I display the position in the list before the item, like the following?

1 lol
2 hey
3 water
4 pepsi
5 jam

This is for a homework assignment.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
david
  • 183
  • 1
  • 2
  • 7
  • 1
    Note all the "+1"s in the answers. Python starts with an index of 0, not 1. So the proper positions are 0, 1, 2, 3, 4 – mauve Jan 12 '16 at 21:45

3 Answers3

26

The best method to solve this problem is to enumerate the list, which will give you a tuple that contains the index and the item. Using enumerate, that would be done as follows.

In Python 3:

for (i, item) in enumerate(hey, start=1):
    print(i, item)

Or in Python 2:

for (i, item) in enumerate(hey, start=1):
    print i, item

If you need to know what Python version you are using, type python --version in your command line.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Leejay Schmidt
  • 1,193
  • 1
  • 15
  • 24
10

Use the start parameter of the enumerate buit-in method:

>>> hey = ["lol", "hey","water","pepsi","jam"]
>>> 
>>> for i, item in enumerate(hey, start=1):
    print(i,item)


1 lol
2 hey
3 water
4 pepsi
5 jam
Iron Fist
  • 10,739
  • 2
  • 18
  • 34
3

Easy:

hey = ["lol","hey","water","pepsi","jam"]

for (num,item) in enumerate(hey):
    print(num+1,item)
Baerus
  • 99
  • 1
  • 8