Python for loops, range and indexes question

How does this code actually work?
def same_values(lst1, lst2):
new_lst =
for index in range(len(lst1)):
if lst1[index] == lst2[index]:
new_lst.append(index)
return new_lst

print(same_values([5, 1, -10, 3, 3], [5, 10, -10, 3, 5]))

“for index in range(len(lst1)):” My understanding is that this line of code means the range in this instance will be range(0, 5) and the length will also be 5.

How is the whole block of code actually checking the value of the indexes? Because if I print this:

lst = [5, 1, -10, 3, 3]
for i in range(len(lst)):
print(i)

The output is

0
1
2
3
4

and not the list of actual values corresponding to the indexes.

I hope I’m making sense.

that is why, in the exercise solution we have this:

``````lst1[index]
``````

the `index` is used to look up the value in the list.

remember, if we have a list, we can access elements by index:

``````the_list[index] # so index could be 0 for example
``````

by using a loop, we can “auto-generate” all the indexes and use those to lookup values in the list(s)

2 Likes

This topic was automatically closed 18 hours after the last reply. New replies are no longer allowed.