Question:
In a Python list
, there are append
and extend
methods.
What is the difference between them and when should I use each one?
Answer:
extend()
Takes an " iterable " as a parameter and extends the list by adding its elements
lista = [1, 2, 3]
lista.extend([4, 5])
print(lista)
# Saída: [1, 2, 3, 4, 5]
append()
add an element to the end of the list
lista = [1, 2, 3]
lista.append([4, 5])
print(lista)
# Saída: [1, 2, 3, [4, 5]]