 Using list comprehension

I managed to use a list comprehension for this. After struggling for a while on the exercise before this one, I managed to get this one in a clean swoop, which resulted in some earnest fist pumping in my rather quiet office.

def odd_indices(lst):
new_list=[e for e in lst if lst.index(e)%2!=0]
return new_list

Someone also mentioned above that using the index() function might miss duplicate numbers; this doesn’t happen in this code.

If we are to assume that advanced topics have not yet come up, then this solution is invalid as it steps outside of the boundaries and scope of the lessons thus far completed. It does not help learners as one might think, but rather distracts them into thinking what they ARE learning is of no value.

Also, by this stage one may assume the learner has a cursory understanding of lists as iterables with indexed values, and of how to iterate over a list to retrieve the values at each index using range() then this is what should be employed in the solution. Only those concepts, nothing more.

odd_indices = range(1, len(lst), 2)    # [1, 3, 5, ...]
new_list = []
for x in odd_indices:
new_list.append(lst[x])    # value at odd index x
return new_list

At this point in the course, we have been over list comprehensions many times…

From:

If that’s the case, then belay, belay. Still tend to harp on naive approaches, that lead to refactored approaches purely for the practice.

I was also successful completing this using list comprehension. I wasn’t sure if the above solution would work all the time due to index ‘skipping’ sometimes (from what i read online). So this is another solution, it uses two list comprehensions to get the job done.

def odd_indices(lst):
odd = [i for i in range(len(lst)) if i % 2 == 1]
new_list = [lst for x in odd]
return new_list