3

I have a homework assignment. 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 this:

1 lol
2 hey
3 water
4 pepsi
5 jam
Wayne Werner
  • 41,650
  • 21
  • 173
  • 260
david
  • 93
  • 1
  • 1
  • 6

3 Answers3

13

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.

Leejay Schmidt
  • 1,038
  • 14
  • 24
7

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
  • 9,767
  • 2
  • 16
  • 31
3

Easy:

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

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