Why wont this code in Code Challenge: Loops Odd Indices work?

https://www.codecademy.com/paths/computer-science/tracks/cspath-flow-data-iteration/modules/dspath-python-loops/lessons/python-functions-loops-cc/exercises/odd-indices

i tried doing this following thing:

def odd_indices(lst):
  odd_lst = [ ]
  for num in range(len(lst) -1):
    if num % 2 != 0:
    	odd_lst.append(lst[num])
    return odd_lst

why does it return instead of making a list with all the items with odd indexes?

Quite possibly, you have an indentation error. If I had to guess, I’d bet you have your return odd_lst statement indented to be inside your for code block. When you post code, click on the </> icon first, and then paste your code in the space indicated. That will preserve your formatting, so we can see exactly what you did. In a language like Python, indentation matters a lot, and we can’t see how your code is indented the way it is currently shown in your post.

As we can see, the return is inside the loop block, hence immediate return of an empty list.

Thanks, for re-posting your code. You just need to out-dent your return statement to be even with for. As it is, the return is executed after the first iteration at index 0, and the function is terminated.

Mod edit, truth be known.

1 Like