How to modify an element inside a list in Python?

3

I have the following list:

pessoa=("Filipe", 40, True)

I write the print command for each element:

print(pessoa[0])
print(pessoa[1])
print(pessoa[2])

The answers are:

Filipe
40
True

When I try to modify the first element:

pessoa[0]="Marconi"
recebo a resposta de erro abaixo:
Traceback (most recent call last):
  File "D:/Licença/Scripts/A5825_Listas.py", line 16, in <module>
   pessoa[0]="Marconi"
TypeError: 'tuple' object does not support item assignment

How do I modify an element of a list in Python?

    
asked by anonymous 10.02.2018 / 07:52

1 answer

2

In fact you are trying to modify a tuple, tuples are like lists, only that is immutable ie once created it can not be modified.

When trying to modify a tuple element:

numeros = (1,2,3,4,5,6,7,8)
print(numeros[2]) # 3
# Ao tentar modificar
numeros[2] = 99 # TypeError: 'tuple' object does not support item assignment

We can not change the elements of the tuple, but we can put list inside it. In the example below, a tuple containing only one element will be added in the tuple numeros .

numeros = (1,2,3,4,5,6,7,8)
print(numeros)
numeros = (99)
print(numeros)
  

See working at repl.it

In your case, we create a new tuple: ('Marconi',) and add in it the elements of the previous tuple + pessoa[1:] , but starting from position 1 to the last position, which in this case is two. Note that the final position has not been reported, so if you have more elements in the tuple, they will also be added in the new tuple.

pessoa=("Filipe", 40, True)
pessoa = ('Marconi', ) + pessoa[1:]
print(pessoa)
  

See working at repl.it

References

10.02.2018 / 08:21