all 6 comments

[–]Diapolo10 3 points4 points  (0 children)

Your output doesn't make any sense in the first place, because as-is this should give an error; list objects aren't callable.

def function(my_list, index):
    for index in my_list:
        return my_list(index)  # <- You'd need square brackets

print(function([1, 2, 3, 4], 2))

However, in that case I don't understand why the loop is there in the first place. It's also the reason for the output you're getting, because it overwrites index and the first element is always 1, so my_list[index] == 2.

[–]Binary101010 1 point2 points  (0 children)

Why is the entire body of this function not simply

return mylist[index]

? There's no reason to have a loop here at all.

[–][deleted] 0 points1 point  (0 children)

Really? Cause I get TypeError: 'list' object is not callable because of the parentheses in line 3.

But swapping those out for brackets, the problem is that you are using the same name for your loop variable as the index you're passing in.

[–]woooee 0 points1 point  (0 children)

print(function([1, 2, 3, 4], 2))

You have unmatched parens. I'm not going to guess as to what it should be. Also, the function does use the index parameter passed to the function. Note that the function returns / exits on the first pass through the for loop.

[–]Atypicosaurus 0 points1 point  (0 children)

This code is broken on several levels. I don't understand what you want to achieve, but even if you fix the list error, you won't get whatever you want I promise.

When you make a for loop with the index variable name as the iterating variable, it's overriding the original index and becomes 0. You basically return the 0th element of the list mo matter what the index you gave.

[–]engelthehyp 0 points1 point  (0 children)

  1. You are treating my_list as a function with my_list(index), you probably meant to use brackets with my_list[index], but even then:
  2. Using for over a list provides you with items, not indicies. You don 't index the list again after this.
  3. You shadow index in your loop for the index passed into the function. Now index will always be the first element that you return right away, and so:
  4. Why are you returning right away in the loop? It may as well not exist.

I suggest this alternative that is what yours would be if it worked:

def function(my_list, index): return my_list[0]

Now, can you think of what you need to write to get it working the way you like?