How can I obtain just the odd indices of a list?


#1

Question

In the context of this code challenge, how can I obtain just the odd indices of a list?

Answer

There are a few ways you can obtain the odd indices of a list. The methods shown here will be how to obtain the indices and not the actual values stored in the list at the indices. Once you have the indices, you can get the actual values easily.

One way is using the range() function, such that it starts at the first odd index, 1, and has a step value of 2, so that it returns the odd indices 1, 3, 5, ....

range(1, len(list), 2)

Another way to obtain the odd indices of a list is using list comprehension, in which you can use a condition that will only include the odd indices.

[i for i in range(len(lst)) if i % 2 == 1]

One other way is to use a for loop over the indices of a list, and using an if statement that checks whether that index is odd, similar to the condition used in the list comprehension above. This method will not be shown here, but feel free to try implementing it on your own!