How do I get a function that returns the odd indices of a list using this approach?

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

The answer simply uses range:

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

That’s all fine.

But I tried to use an if statement. If the index in a list is odd* (the index, mind you, and not the element of the list), then append that to a modified list. However, even though I think the following code should output all of the values from every odd index in a list (1, 3, 5 etc.), it doesn’t when I put in a list as an argument.

def odd_index(your_list):

        modded_list=[]

        for index in your_list:

                if index < len(your_list) and index % 2 != 0:

                        modded_list.append(your_list[index])    

        return modded_list

I realise this:

for index in your_list:

and this even:

if index

is referring to the actual item of the list, not its index. How do I refer to the index?

The surest way to refer to the index is to use a range.

for i in range(len(lst)):

Now you can use the if statement on i, and if odd, assign lst[i] to the new list.

Be not tempted to use the index() method as it will always return the same, first encountered value’s index, not necessarily the current item. That’s why,

for x in lst:

is not a valid approach.

We’re jumping ahead, so don’t try to use this until it actually comes up in the iterators unit (assuming it does). There is a method called, .enumerate() which creates a consumable object of index, value pairs.

for i, x in enumerate(lst):
    if i % 2:
        new_lst.append(x)

To repeat, wait for the topic of iterators comes up in the lessons as they have some unique properties that are best learned at once, so we learn how to implement them correctly.

1 Like