In a list, what is the difference between append and extend?

Asked

Viewed 7,080 times

15

Num list in Python, there are the methods append and extend.

What’s the difference between them and when to use each?

3 answers

16


extend()

Gets a "iterable" as 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()

adds an element at the end of the list

lista = [1, 2, 3]
lista.append([4, 5])
print(lista) 
# Saída: [1, 2, 3, [4, 5]]
  • 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?

  • @vnbrs O extend yes

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

  • 1

    I took the liberty of changing array for list, my young man :p

  • @Wallacemaxters of my habit force :) Thank you

Browser other questions tagged

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