Can I use `index()` for the loop challenge?

the solution to this challenge was quite straight forward, but i did it the stupid way using .index():

#Write your function here
def odd_indices(lst):
  new_lst = []
  for item in lst:
      if lst.index(item)%2==1:
  return new_lst

#Uncomment the line below when your function is done
print(odd_indices([4, 3, 7, 10, 11, -2]))

No way is ‘stupid’ though some do come with provisos and gotchas. list.index() has one of its own. What if there are duplicates in the list? .index() will only ever find the first one. In this exercise we wouldn’t need to know the index in this way.

We know that a list has a sequential index starting at 0. Zero is even so we would want to start one space over, with 1. Next we go to 3, then 5, then 7, and so on, in steps of 2. Sounds like a job for range since it can be started and stopped anywhere, and we can step in any stride length.

range(1, len(lst), 2)

After that it’s just a matter of appending the value at the current index to the return list. No if's about it.


when you look at it from that perspective , it makes complete sense!
much love for the detailed explanation <3

1 Like

Hi is there a way to check what position an index has in a list? i was trying to do it with %2 != 0 method

We can use the .index() method if we are sure there is but one item, and no duplicates since this method will only return the index of the first item it finds.

>>> a = [2,5,8,9,3,2,5,8]
>>> a.index(8)

Unless we spin off a shortened slice, we will not get to the other 8.

>>> b = a[a.index(8)+1:]
>>> b.index(8)

We do have a tool that we can use to find all the indices, but it will take some reckoning…

>>> c = [i for i, x in enumerate(a) if x == 8] # i is the index, x the item
>>> c
[2, 7]
1 Like
def odd_indices(lst):
  return [elem for elem in lst if lst.index(elem) % 2 != 0]

If I do it this way will it not also cover the edge cases like when there are 2 same elements?

Never mind. It’s basically the same thing as the example that started this thread and I think I understand the problem now. The range function makes more sense in this case. Thank you!