# (Loops) Same Values in lists

I came across a function that made no sense to me. I thought the function was built to report what numbers appeared to be in both indexes. Somebody please help.

Screen Shot 2020-10-05 at 5.49.51 PM|690x417

Ok, so this is the code from the screenshot:

``````def same_values(lst1, lst2):
equal_values = [];
for index in range(len(lst1)):
if lst1[index] == lst2[index]:
equal_values.append(index)
return equal_values

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

I’m going to go step by step:

1. We define a function called same_values with 2 parameters, `lst1` and `lst2`
2. Inside the function, we declare an empty array `equal_values`
3. We set a for loop to go from `0` to `len(lst1)`. This means that `index` in that for loop will take the values 0, 1, 2, … and so on until it equals the size of array `lst1`
4. Inside the for loop, we have a conditional statement that checks the item in `lst1` in position `index` to see if its equal (`==`) to item in `lst2` in position `index` as well. So has the for loop iterates, this `if` statement will ask the question “is `lst1[0]` equal to `lst2[0]`?”, and the next iteration: “is `lst1[1]` equal to `lst2[1]`?” and so on for as long as many iterations of the for loops as there are.
5. If the conditional statement is true, inside of it we use `.append(index)` to add the value of `index` at that moment (remember, it goes from `0` to `len(lst1)`) to the empty array we declared at the start of the function.
6. After the for loop has run its course, the function returns the array `equal_values`
7. Finally, a we call the function `equal_values` inside a `print` statement so that when the function returns the array `equal_values` we can see it printed in the console. We call the function with 2 arrays in this example: `[5, 1, -10, 3, 3]` and `[5, 10, -10, 3, 5]`, which will become `lst1` and `lst2` inside the function
2 Likes

Step by step execution:

``````lst1 = [5, 1, -10, 3, 3]
lst2 = [5, 10, -10, 3, 5]
equal_values = []
len(lst1) = 5 ---> range(5) = 0, 1, 2, 3, 4
First iteration for loop: index = 0
lst1[0] = 5
lst2[0] = 5
is 5 equal to 5? = YES
equal_value.append(5) ---> equal_value = [5]

Second iteration for loop: index = 1
lst1[1] = 1
lst2[1] = 10
is 1 equal to 10? = NO

Third iteration for loop: index = 2
lst1[2] = -10
lst2[2] = -10
is -10 equal to -10? = YES
equal_value.append(-10) ---> equal_value = [5, -10]

Fourth iteration for loop: index = 3
lst1[3] = 3
lst2[3] = 3
is 3 equal to 3? = YES
equal_value.append(3) ---> equal_value = [5, -10, 3]

Fifth iteration for loop: index = 4
lst1[4] = 3
lst2[4] = 5
is 3 equal to 5? = NO

END of for loop (we finished the values in range(5))
Return [5, -10, 3]
``````
2 Likes

Thank you for the clarification, this makes much more sense.

1 Like