How do you print a specific item from a list??
mylist = ["banana", "cherry", "apple"]
for i in mylist :
print(mylist[0])
When I run the above code it prints…
banana
banana
banana
And I don’t know how to fix it.
How do you print a specific item from a list??
mylist = ["banana", "cherry", "apple"]
for i in mylist :
print(mylist[0])
When I run the above code it prints…
banana
banana
banana
And I don’t know how to fix it.
It’s iterating over the list, assigning i
to each item, so:
for i in mylist:
print(i)
Hi,
when working with lists, note that each item in the list corresponds to an index number, starting from 0
(i.e., its location in the list, starting from 0
and and increasing 1
, 2
, …, n
). This is why when you iterated through the list, and you had the index fixed to 0
, it always printed banana
. By iterating through the list, and not having the index value to a fixed value, allows you to iterate through all of the values in the list.
Here is an example where we make use of the enumerate
keyword to iterate through the list values while simultaneously keeping tabs on the index value.
mylist = ["banana", "cherry", "apple"]
for index, item in enumerate(mylist):
print(f'mylist[{str(index)}] = {item}')
I’m guessing that your mental model is that on each iteration of the loop, mylist[0]
refers to the “next” item of the list.
There is an anonymous list iterator that tracks the “walk” through mylist
; the name mylist
itself is not that iterator: it always refers to the list itself. i
gets its value (an element of the list) from the list iterator, not from the list directly.