Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I display the the index of a list element in Python? [duplicate]

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.

like image 643
david Avatar asked Nov 27 '22 13:11

david


1 Answers

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.

like image 81
Leejay Schmidt Avatar answered Dec 15 '22 02:12

Leejay Schmidt