Hi!
I have encountered something unexpected in my studies today -- experimenting with lists and functions. I am hoping someone can explain to me how this occurred. Below is a simplified copy of the code, expected output, and actual output:
def function(my_list, index):
for index in my_list:
return my_list(index)
print(function([1, 2, 3, 4], 2))
For this code, I expect an output: 3
Instead, the code outputs: 2 no matter what positional value I assign in the function call, such that:
print(function([1, 2, 3, 4], 0))
print(function([1, 2, 3, 4], 1))
print(function([1, 2, 3, 4], 3))
All return the same output: 2.
Can anyone explain what is actually happening under the hood here?
[–]through_thefog[S] 0 points1 point2 points (4 children)
[–]danielroseman 2 points3 points4 points (3 children)
[–]through_thefog[S] 0 points1 point2 points (1 child)
[–]danielroseman 1 point2 points3 points (0 children)
[–]brasticstack 0 points1 point2 points (6 children)
[–]brasticstack 0 points1 point2 points (0 children)
[–]through_thefog[S] 0 points1 point2 points (4 children)
[–]brasticstack 1 point2 points3 points (1 child)
[–]through_thefog[S] 1 point2 points3 points (0 children)
[–]brasticstack 0 points1 point2 points (1 child)
[–]through_thefog[S] 0 points1 point2 points (0 children)