How to modify an element within a Python list?

Asked

Viewed 6,347 times

4

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 from a Python list?

1 answer

3


In fact you are trying to modify a tuple, tuples are like lists, only immutable that is, once created cannot 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 will be added in tuple numeros a tuple containing only one element.

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

See working in repl it.

In your case, we create a new tuple: ('Marconi',) and add to it the elements of the previous tuple + pessoa[1:], but starting from position 1 to the last position, which in case is two. Note that the final position has not been informed, 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 in repl it.

References

  • 4

    AP clearly asked "list" - so he’s confusing lists and tuples - I think a legal answer should address that and explain the difference.

Browser other questions tagged

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