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

13

In list in Python, there are methods append and extend .

What's the difference between them and when should I use each?

    
asked by anonymous 09.12.2016 / 20:38

3 answers

13

extend()

" 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 at the end of the list

lista = [1, 2, 3]
lista.append([4, 5])
print(lista) 
# Saída: [1, 2, 3, [4, 5]]
    
09.12.2016 / 20:42
11

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 .

    
09.12.2016 / 20:43
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 iterá the elements, it would be almost like a "merge"

    foo = [1, 2, 3]
    foo.extend([4, 5])
    print foo
    

    Returns: [1, 2, 3, 4, 5]

From the SOen: link

Example on ideone: link

    
09.12.2016 / 20:41