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

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!

16 Likes

You could also slice the list. For example:

lst[1::2]

This will return only the odd indices of the list

39 Likes

That’s right. Also del [: : 2] will delete all even indices and return odd indices numbers. :slight_smile:

10 Likes

Now I am not 100% sure about this, but I think the solution given by the course fails when the list provided has an odd number of elements because by using the range with the length of the list, it will automatically exclude the last element of the list.

1 Like

if that is the case, the challenge is to write code to prove this

i don’t think it will happen, given range/len starts counting at one while indices start at zero

so if have the following list:

[1, 2, 3, 4, 5]

the length is 5 while the highest index is 4

1 Like

When I was on that exercise, I added an element to the list of the example and the solution provided did not print it, which was when I decided to post my previous reply.

so you claim this:

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

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

doesn’t work? Works fine, 6 is an even index, so it make sense it isn’t added.

next time, please add a code sample to prove your point. thank you

2 Likes

I think there’s a correction in the way you used the list comprehension. Let me know if I’m wrong:

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

print(odd_indices([4, 3, 7, 10, 11, -2]))

5 Likes

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

print(odd_indices([4, 3, 7, 10, 11, -2]))

How come when I run this code it returns [1, 3, 5]?
It seems it is giving me the odd indices but not their values…

Look at the post just above yours. See the difference?

1 Like

Hello can you please help me?

def odd_indices(lst):
  odd_indices_lst=[]
  for i in range(1,len(lst),2):
    odd_indices_lst.append(lst[i])
    
  return odd_indices_lst
#Uncomment the line below when your function is done
print(odd_indices([4, 3, 7, 10, 11, -2]))

this way the code works as it is supposed to. evereything seems fine.

I tried to remove the append command and use the += command instead.

instead of writting odd_indices_lst.append(lst[i])

i tried writting odd_indices_lst += lst[1] and i ended up with an TypeError: ‘int’ object is not iterable.

Could you please explain why the += doesn’t work in this example?

Thank you very much.

You can “add” (I.e., make use of the + operator) a list to another list (equivalent to lst.extend), but you must append an object of a different type to a list.

1 Like

so the difference is that append adds any type of object to a list, but in order to use + or += you must add an object of the same type.?

is that why if i put the +=lst[1] into [] brackets it works perfectly?

def odd_indices(lst):
  odd_indices_lst=[]
  for i in range(1,len(lst),2):
    odd_indices_lst+=[(lst[i])]
  return odd_indices_lst
                 

after all cleared up, why should i choose append over the += or why should i choose += over append? Im asking specifically for this exercise.

that seems interesting. could you explain how does this work?

its already mentioned? + is list extending. This should give you what you need to start some research:

https://www.geeksforgeeks.org/append-extend-python/

1 Like

Not quite: += or lst.extend() work to “append” the entire contents of a list to a given list. The material to be added must be within a list.

It just depends on what you are trying to do.

If I want to add an int to a list of ints, why would I want to create an extra step of first putting my int inside a list just so that I could use +=, when I have append() available?

On the other hand, if I have a list of int whose elements I’d like to tack on to an existing list, why go through the first list and do for-in-append() for each element when I have extend (or += ) available?

1 Like

On the other hand, if I have a list of int whose elements I’d like to tack on to an existing list, why go through the first list and do for-in-append() for each element when I have extend (or += ) available?

Yes, but coulnd’t you just use .append() like that :

list_a.append(list_b) 

correct me if i’m wrong but isn’t that possible?

It’s really a matter of choosing one method or the other.

[1, 2, 3] + [4, 5, 6]        =>  [1, 2, 3, 4, 5, 6]

[1, 2, 3].extend([4, 5, 6])  =>  [1, 2, 3, 4, 5, 6]

We cannot append multiple values in one expression, so this won’t work…

>>> [1, 2, 3].append(4, 5, 6)

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    [1, 2, 3].append(4, 5, 6)
TypeError: append() takes exactly one argument (3 given)

and if we attempt to append a list, we get this,

>>> a = [1, 2, 3]
>>> a.append([4, 5, 6])
>>> a
[1, 2, 3, [4, 5, 6]]
>>> 
4 Likes

here is my workaround :

def odd_indices(lst):
  return [lst[i] for i in range(len(lst)) if i % 2 != 0]
   

print(odd_indices([4, 3, 7, 10, 11, -2]))
#[3, 10, -2]

any comments on it ?

We would have to conclude that list comprehensions have already been taught, which may not in fact be the case at this point for most learners. Can you confirm that solution should be on the table?

If we take comprehensions off the table, we may still use range to isolate the odd indices.

result = []
for i in range(1, len(lst), 2):
    result.append(lst[i])
return result
1 Like