Codecademy Python: Code Challenges Loops Help

def odd_indices(my_list):
  new_list = []
  n = 0
  for num in my_list:
    if (2*n + 1) % 2 == 0:
      n += 1
    elif (2*n + 1) % 2 != 0:
      new_list.append(my_list[n])
      n += 1
  return new_list

https://www.codecademy.com/courses/learn-python-3/articles/python-code-challenges-loops

It just returns the original list when called. What am I missing ? Thanks in advance.

1 Like

If n is an integer, then (2*n + 1) will always be an odd number regardless of whether n is an even or odd integer. Experiment with different odd and even values of n to confirm this yourself.

Since (2*n + 1) is an odd number, it isn’t divisible by 2.

Hence your if condition    if (2*n + 1) % 2 == 0:    will never be true, whereas your elif condition     elif (2*n + 1) % 2 != 0:     will always be true. Unsurprisingly, you end up appending all elements of the original list to new_list.

1 Like

Thanks so much! Really appreciated.

1 Like