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
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
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.
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
Easy:
hey = ["lol","hey","water","pepsi","jam"]
for (num,item) in enumerate(hey):
print(num+1,item)