Skip to content
Logo do Site
hackerbr.net

  • Início
    • Sobre (About)
  • Política de Privacidade (Privacy Policy)
  • Contato (Contact)
  • Linguagens (languages)
    • HTML
    • Python
  • Banco de Dados (Database)
  • Cybersecurity
  • Computação Forense (Computer Forensics)
  • Anki Web
  • Baralhos Anki
  • Computadores (Computers)
    • Sistemas Operacionais (Operating System)
    • Redes de Computadores (Computer network)
Logo do Site
hackerbr.net

março 24, 2024março 24, 2024

Como alterar elementos de uma lista em Python? (How to change elements of a list in Python?)

Em Português:

Para alterar elementos em uma lista em Python, você atribui um novo valor diretamente ao índice desejado. Aqui está um exemplo:

# Suponha que temos uma lista
minha_lista = ['maçã', 'banana', 'cereja']

# Alterar o segundo item
minha_lista[1] = 'amora'

# Agora, minha_lista é ['maçã', 'amora', 'cereja']

Você também pode alterar uma série de itens atribuindo uma nova lista de valores ao fatiamento da lista:

# Alterar o segundo e terceiro itens
minha_lista[1:3] = ['amora', 'melancia']

# Agora, minha_lista é ['maçã', 'amora', 'melancia']

Lembre-se, o índice em listas Python começa em 0, então minha_lista[1] refere-se ao segundo item na lista.

In English:

To change elements in a Python list, you directly assign a new value to the desired index. Here’s an example:

# Assume we have a list
my_list = ['apple', 'banana', 'cherry']

# Change the second item
my_list[1] = 'blackcurrant'

# Now, my_list is ['apple', 'blackcurrant', 'cherry']

You can also change a range of items by assigning a new list of values to the slice of the list:

# Change the second and third items
my_list[1:3] = ['blackcurrant', 'watermelon']

# Now, my_list is ['apple', 'blackcurrant', 'watermelon']

Remember, the index in Python lists starts at 0, so my_list[1] refers to the second item in the list.

References:

[1]F. Laiq, “How to Swap Elements of a List in Python,” Delft Stack, Feb. 02, 2024. [Online]. Available: https://www.delftstack.com/howto/python/python-swap-elements-in-list/

[2]“How to Update List Element Using Python Examples,” Tutorialdeep, Aug. 06, 2021. [Online]. Available: https://tutorialdeep.com/knowhow/update-list-elements-python/

[3]Nik, “Python: Replace Item in List (6 Different Ways),” datagy, Aug. 12, 2022. [Online]. Available: https://datagy.io/python-replace-item-in-list/

[4]“Python – Change List Items.” [Online]. Available: https://www.w3schools.com/python/python_lists_change.asp

Python

Navegação de Post

Previous post
Next post
©2026 hackerbr.net | WordPress Theme by SuperbThemes