How do I display the the index of a list element in Python?
51,566
Solution 1
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.
Solution 2
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
Solution 3
Easy:
hey = ["lol","hey","water","pepsi","jam"]
for (num,item) in enumerate(hey):
print(num+1,item)
Author by
david
Updated on May 06, 2020Comments
-
david about 4 years
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
-
ᴀʀᴍᴀɴ over 8 yearsno need for space between them
,
also adds a space -
Leejay Schmidt over 8 years@Arman Thanks! Corrected it.
-
david over 8 yearswhy did you put the -V in i,v
-
Iron Fist over 8 years@dragyitutorial what -V ?...i is the index, v is the item at that index...
-
Iron Fist over 8 years@dragyitutorial, I've replaced v with item, does it make sense now?
-
david over 8 yearsok , learned something , but can the -V be another random letter
-
david over 8 yearsand why do i need to put the item at the index (Sorry for stupid question)
-
Iron Fist over 8 years@dragyitutorial .. I suggest you take a read the doc from here
-
david over 8 years@LeejaySchmidt im in high school , so can you explain to me what does --hey.index(item)+1,item-- mean , i dont uderstand why did you put --index(item)+1 and why did you put --,item at the end
-
Leejay Schmidt over 8 yearsArrays in Python start indexing at
0
, so you have to haveindex(item)+1
to start printing the indexes at1
instead of0
(otherwise you would get0 lol
and1 hey
, etc.). The,item
concatenates thestring
representation of the item with what is preceding the comma, otherwise it would just print out the index. -
david over 8 years@LeejaySchmidt Thanks , really appreciated.
-
Leejay Schmidt over 8 yearsNo problem. Have fun learning!
-
Tom Zych over 8 yearsWon't work correctly if there are repeated items. And wow, it's kind of inefficient to do a lookup in every iteration.
-
Leejay Schmidt over 8 years@TomZych Good points, and they're well taken. I've updated the answer to reflect this.
-
Thierry Lathuille about 4 yearsThe first two pieces of code are really bad advice and should be deleted. Using
enumerate
is the way to go. -
Leejay Schmidt about 4 years@ThierryLathuille I agree. I have removed the methods that involved a traversal of the list first, and now only recommend enumerating the list.