I am a beginner in the python world and I really like this language so far!
In my exercices session I’ve found the following one: "Use a loop to display elements from a given list present at odd index positions" and I’ve come to 2 solutions.
However I cannot see why the following 2 snippets of code are not prompting the same result.
1st one:
#THIS ONE IS WORKING
my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
for index in range(len(my_list)):
#print(type(index), end=" ")
if index % 2 != 0:
print(my_list[index], end=" ")
2nd one:
#THIS ONE IS **NOT** WORKING
my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
for item in my_list:
#print(type(item), end=" ")
if item % 2 != 0:
print(item, end=" ")
As you can see I’ve thought that maybe the elements are not an integer for the 2nd snippet and that’s why I’ve tried to print the type.
So the result should be for both snippets:
20 40 60 80 100
And for the 2nd one I receive no output.
Can you help me in understanding why? And sorry beforehand if it’s something very trivial for you that I did not see. Not even ChatGPT could’ve help me here…
>Solution :
Welcome to Python!
For your question, you are looping two different lists, if you print the item in each iteration, you will see
for index in range(len(my_list)):
outputs of index: 0,1,2,3,...
for item in my_list:
outputs of item: 10,20,30,40,50,...
To fix this for the second loop, do
for item in my_list:
if my_list.index(item) % 2 != 0:
print(item, end=" ")
Edit: thanks @buran & @slothrop for pointing out the mistake