In list
in Python, there are methods append
and extend
.
What's the difference between them and when should I use each?
In list
in Python, there are methods append
and extend
.
What's the difference between them and when should I use each?
In% w_that you add elements to the end of the list, in% w_that an iterable is expected as argument, and this argument is appended to the end of the element by element list.
If you have a list and want to include elements from another list in it, you should use append()
; otherwise it will add a list to the end of your list.
Example:
lista1 = [1, 2, 3]
lista1.append([4, 5])
print lista1
# resultado: [1, 2, 3, [4, 5]]
lista2 = [1, 2, 3]
lista2.extend([4, 5])
print lista2
# resultado: [1, 2, 3, 4, 5]
lista3 = [1, 2, 3]
lista3.append(4)
print lista3
# resultado: [1, 2, 3, 4]
See working at Ideone .