Variable definition within a loop?

I am confused as to why this doesn’t work for me. When I run the code it only prints the last index that’s negative When I print(odd_elements) it prints the proper output.

def odd_indices(lst):
  for odd in range(len(lst)):
    odd_elements = []
    if (odd % 2 == 1):
      odd_elements.append(lst[odd])
  return odd_elements 

This list definition should not be inside the loop, but before it.

ohh! could you give me an example of when the variable definition would go in the loop? Thank you

When it precedes an inner loop, otherwise, practically never. All initialization should take place outside of the loop, and only change inside the loop.