Removing elements from a list

0

I'm having problems 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)
  • Item 2 is simply not recognized

  • IndexError: list assignment index out of range
    

    Could anyone help me solve this problem?

        
    asked by anonymous 30.10.2018 / 21:27

    1 answer

    2

    The list is a direct sequence of values, they are not associated with the index. So by removing an element from the middle of the list, all the elements ahead are "moved".

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

    • Element 0 is 'a' ( lista[0] )
    • Element 1 is 'b' ( lista[1] )
    • Element 2 is 'c' ( lista[2] )

    When you remove the element 0 (with del lista[0] ) the list looks like this: ['b', 'c']

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

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

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

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

    A common way to solve this problem is to remove the elements always by ordering from back to front, ie removing the element 2 first, then the 1 and finally the 0 , as this prevents the items that will still be removed in the future.

        
    30.10.2018 / 22:17