Home > Software design >  Need to remove every third element in a list of 10 elements - getting index error
Need to remove every third element in a list of 10 elements - getting index error

Time:05-21

I keep getting IndexError: list assignment index out of range. My logic is as follows: The print(x) shows that 6 is printed out before getting the error. Working through the code logically, 6 % 4 == 0 is true, so the code should delete numbers[6 - 1] which is numbers[5]. After that, x is incremented to 7, and the loop will not iterate again.

Can someone please point out where I am incorrect? TIA.

# create list from user specifications
numbers = []
size = int(input("Enter the number of elements: "))

for i in range(0, size):
    numbers.append(int(input("Enter an element: ")))

# Iterate through each element. If an elements index is a multiple of 3,
# delete it.
x = 1
while x <= size:
    print(x)
    if ((x) % 3) == 0:
        del(numbers[x - 1])
    x = x   1

print("The list is: ")
print(numbers)

CodePudding user response:

The problem is that the array changes size during the loop. When the index is indeed a multiple of three, the del operation removes the element from the array, thus numbers no longer have a size of size, but your index variable x will still go up to the value of size-1 which is above the last index of your modified array.

An easy way is to build a copy of the list instead of removing elements from it, and ignoring all elements with index multiple of 3.

# create list from user specifications
numbers = []
size = int(input("Enter the number of elements: "))

for i in range(0, size):
    numbers.append(int(input("Enter an element: ")))

# Iterate through each element. If an elements index is a multiple of 3,
# delete it.
x = 1
filtered = []
while x <= size:
    print(x)
    if not ((x % 3) == 0):
        filtered.append(numbers[x-1])
    x = x   1

numbers = filtered 

print("The list is: ")
print(numbers)

CodePudding user response:

When you delete an item in a list, the remaining items shift left, changing their index. After the first delete, you either have to change your index value or use a different technique completely. Python is well suited for filtering lists with "comprehensions". Use that, and the enumerate function that will emit the values plus their index, and you can simplify this greatly.

numbers = [1,2,3,4,5,6,7,8,9,10]
numbers = [value for index, value in enumerate(numbers, 1) if index % 3]
print(numbers)
            
  • Related