The reason your code doesn't work is because
for count in fruit:
iterates over each item in the fruit
list, so once you're at the half-way point, item
will point beyond the end of the list. Here's a modified version of your code to illustrate:
item = 0
fruit = ['Strawberry', 'apple', 'pear', 'orange', 'banana', 'cucumber', 'tomato', 'Kiwi']
print(len(fruit))
for v in fruit:
print(v, item)
item = item + 2
output
8
Strawberry 0
apple 2
pear 4
orange 6
banana 8
cucumber 10
tomato 12
Kiwi 14
So once we reach "banana", fruit[item]
will try to access an item beyond the end of fruit
, and that raises an IndexError
exception.
As others have mentioned, the usual way to do this task in Python is to use extended slicing:
fruit = ['Strawberry', 'apple', 'pear', 'orange', 'banana', 'cucumber', 'tomato', 'Kiwi']
for v in fruit[::2]:
print(v)
output
Strawberry
pear
banana
tomato
If you want the odd items, you can start the slice at 1:
for v in fruit[1::2]:
print(v)
output
apple
orange
cucumber
Kiwi
Or you can just print a slice, as is, since it's just a list:
print(fruit[::2])
output
['Strawberry', 'pear', 'banana', 'tomato']