Removing elements from a list

Asked

Viewed 1,303 times

0

I’m having trouble with my code.

print('inserindo e removendo itens da lista\n')

bom_dia = []

bom_dia.insert(0, 'python')
bom_dia.insert(1, 'a')
bom_dia.insert(2, 'b')

print(bom_dia)

print()


del bom_dia[0]
print(bom_dia)

del bom_dia[1] # 1
print(bom_dia)

del bom_dia[2] # 2
print(bom_dia)
  1. Has a bug, deleting item 'b' and not 'a'

  2. Item 2 is simply not recognized

IndexError: list assignment index out of range

I wonder if someone could help me solve this problem?

  • 3

    When you remove position 0, the list has two values: 'a' at position 0 and 'b' at position 1. When you remove position 1, you are removing 'b' and when you try to remove position 2, it is wrong, since at that point the list will have only 'a' at position 0.

1 answer

3


The list is a direct sequence of values, they are not associated with the index. Then, when removing an element from the middle of the list, all elements in front are "shifted".

For example, if you have a list with 3 elements lista = ['a', 'b', 'c']

  • The element 0 is the 'a' (lista[0])
  • The element 1 is the 'b' (lista[1])
  • The element 2 is the 'c' (lista[2])

When removing the element 0 (with del lista[0]) the list goes like this: ['b', 'c']

  • The element 0 now is the 'b' (lista[0])
  • The element 1 now is the 'c' (lista[1])
  • There is no more element 2

Then you remove the element 1 (with del lista[1]), the list goes like this: ['b']

  • The element 0 now is the 'b' (lista[0])
  • There is no more element 1 nor 2, the list has only one element

Finally, when trying to remove the element 2 (with del lista[2]) you receive the error because the list no longer has the element 2.

A common way to solve this problem is to remove the elements always ordering backwards, ie remove the element 2 first, then the 1 and finally the 0, as this prevents the displacement of items that will be removed in the future.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.