Python delete all elements from a list that are on an odd index
Question:
I’m trying to delete all elements from a Python list that are on an odd index of the list. In my case, the result from len(elements)
is 40, so I assume after deleting all odd indexes, the total length should be 20. I tried the following code:
indx = 0
for element in elements:
if indx % 2 == 1:
elements.remove(element)
indx += 1
After this, the result of len(elements)
is 27, shouldn’t it be 20 since I deleted half of the elements?
Answers:
It may be easier to just recreate the list with the indexes you want, e.g., by using a slice:
elements = elements[0::2]
Because when you delete an element, it will mess up with the for
loop. You can check with this piece of code:
indx = 0
elements = list(range(40))
for element in elements:
print(element, indx)
if indx % 2 == 1:
elements.remove(element)
indx += 1
print(len(elements))
and it prints:
0 0
1 1
3 2
4 3
6 4
7 5
9 6
10 7
12 8
13 9
15 10
16 11
18 12
19 13
21 14
22 15
24 16
25 17
27 18
28 19
30 20
31 21
33 22
34 23
36 24
37 25
39 26
27
As you can see, because you are iteratively removing elements, for element in elements
do not loop all 40 items.
In this case, it is better to use elements = elements[0::2]
like the other answer.
You can create a new list for only the even indexes
new_elements = []
for i in range(len(elements)):
if i % 2 == 0:
new_elements.append(elements[i])
elements = new_elements
else you can make a list compare
elements = [elements[i] for i in range(len(elements)) if i % 2 == 0]
I’m trying to delete all elements from a Python list that are on an odd index of the list. In my case, the result from len(elements)
is 40, so I assume after deleting all odd indexes, the total length should be 20. I tried the following code:
indx = 0
for element in elements:
if indx % 2 == 1:
elements.remove(element)
indx += 1
After this, the result of len(elements)
is 27, shouldn’t it be 20 since I deleted half of the elements?
It may be easier to just recreate the list with the indexes you want, e.g., by using a slice:
elements = elements[0::2]
Because when you delete an element, it will mess up with the for
loop. You can check with this piece of code:
indx = 0
elements = list(range(40))
for element in elements:
print(element, indx)
if indx % 2 == 1:
elements.remove(element)
indx += 1
print(len(elements))
and it prints:
0 0
1 1
3 2
4 3
6 4
7 5
9 6
10 7
12 8
13 9
15 10
16 11
18 12
19 13
21 14
22 15
24 16
25 17
27 18
28 19
30 20
31 21
33 22
34 23
36 24
37 25
39 26
27
As you can see, because you are iteratively removing elements, for element in elements
do not loop all 40 items.
In this case, it is better to use elements = elements[0::2]
like the other answer.
You can create a new list for only the even indexes
new_elements = []
for i in range(len(elements)):
if i % 2 == 0:
new_elements.append(elements[i])
elements = new_elements
else you can make a list compare
elements = [elements[i] for i in range(len(elements)) if i % 2 == 0]