15
Num list
in Python, there are the methods append
and extend
.
What’s the difference between them and when to use each?
15
Num list
in Python, there are the methods append
and extend
.
What’s the difference between them and when to use each?
16
11
In the append()
you add elements to the end of the list, in extend()
a iterable as argument, and this argument is added 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 the extend()
; otherwise it will add a list at 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 on Ideone.
9
append
will add any list
as an item
foo = [1, 2, 3]
foo.append([4, 5])
print foo
Returns: [1, 2, 3, [4, 5]]
extend
the elements would be almost like a "merge"
foo = [1, 2, 3]
foo.extend([4, 5])
print foo
Returns: [1, 2, 3, 4, 5]
Of Soen: https://stackoverflow.com/a/252711/1518921
Example in the ideone: http://ideone.com/2EgMan
I took the liberty of changing array
for list
, my young man :p
@Wallacemaxters of my habit force :) Thank you
Browser other questions tagged python list
You are not signed in. Login or sign up in order to post.
I know it’s not nice to compare other languages with Python, until it brings other customs to Python. But it would be equivalent to
List<T>.AddRange()
of . NET?– vinibrsl
@vnbrs O
extend
yes– Jéf Bueno