1

In the following list

[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

I would like to remove the bottom half of the list, 11-15 However when I try the code below, even though the index seems correct I'm left with wrong parts of my original list

x = list(range(11,21))
print(x) #[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

i = list(range(0,(int(len(x)/2)))) #[0, 1, 2, 3, 4]

for n in i:
    print(x[n]) #Correctly prints 11-15

for n in i:
    del x[n]

print(x) #[12, 14, 16, 18, 20]

How do I modify this so that I remove the first half of a list regardless of size based on index?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
ramadhuta
  • 55
  • 3

3 Answers3

1

When you del x[n], you shift all the indices of the list over which means you access the wrong elements. It's better to just make the indices to remove a set then filter over the range:

i_set = set(i)
filtered_x = [x[n] for n in range(len(x)) if n not in i_set]

Alternatively, if you're removing a contiguous chunk, then just slice the list:

filtered_x = x[len(x)//2:]
Aplet123
  • 33,825
  • 1
  • 29
  • 55
1

You shouldn't modify a list while iterating over it, as the elements the indexes point to will change.

IMHO, the easiest way to remove half the list is to slice it off, and assign the resulting list back to x:

x =  x[len(x) // 2 - 1:]
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

This code for a better understanding of what happens with your code:

x = list(range(11,21))
print(x) #[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

i = list(range(0,(int(len(x)/2)))) #[0, 1, 2, 3, 4]

for n in i:
    print("Before del: ", x[n])
    del x[n]
    print("All list: ", x)
    print("After del: ", x[n])
    print("-----------------")

print(x) #[12, 14, 16, 18, 20]
dimay
  • 2,768
  • 1
  • 13
  • 22