Odd indices code challenge help

In the CS, Loops, “Odd indices” challenge: https://www.codecademy.com/paths/computer-science/tracks/cspath-flow-data-iteration/modules/dspath-python-loops/lessons/python-functions-loops-cc/exercises/odd-indices

If I run the following 2 blocks of code:

new_list = []
def odd_indices(lst):
    for index in range(1, len(lst), 2):
        new_list.append(lst[index])
    return new_list


print(odd_indices([4, 3, 7, 10, 11, -2]))
def odd_indices(lst):
  new_lst = []
  for index in range(1, len(lst), 2):
    new_lst.append(lst[index])
  return new_lst


print(odd_indices([4, 3, 7, 10, 11, -2]))

It returns: [3, 10, -2].

However, in the first instance, where the new list is created outside of the function, it says that it is wrong and that it returns this: [3, 10, -2, 3, 10, -2] although that is not what it returns for me in the online IDE or in Python.

Can someone please explain what is going on here? Thank you!

1 Like

Scope and global variables!

Because you define new_list outside the function it has a global scope (in the second example, it has a local scope). So if you run the function multiple times it will keep adding the extra arrays to your new_list.

One early principle in functions is that they should be self-contained when possible (not always possible, but it’s a good principle to start with).

Hope this helps, and welcome to the forums!

2 Likes

This totally explains it. Thank you!

2 Likes

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.