views:

2176

answers:

5

What is the difference between the list methods append and extend?

+6  A: 

append appends a single element. extend appends a list of elements.

Note that if you pass a list to append, it still adds one element:

>>> a = [1, 2, 3]
>>> a.append([4, 5, 6])
>>> a
[1, 2, 3, [4, 5, 6]]
Greg Hewgill
+14  A: 

append adds an element to a list, extend concatenates lists together.

>>> li = ['a', 'b', 'mpilgrim', 'z', 'example']
>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li.append("new")               
>>> li
['a', 'b', 'mpilgrim', 'z', 'example', 'new']
>>> li.insert(2, "new")            
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new']
>>> li.extend(["two", "elements"]) 
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']

From Dive into Python.

Harley
Note, `extend` doesn't just concatenate lists, it extends a list with an arbitrary iterable.
Mike Graham
+6  A: 

append:

x = [1, 2, 3]
x.append([4, 5])
print (x)

gives you [1, 2, 3, [4, 5]]

extend:

x = [1, 2, 3]
x.extend([4, 5])
print (x)
[1, 2, 3, 4, 5]
kender
+5  A: 

Good answers, but don't forget, any iterable will do for extend (not just list):

l.extend(xrange(5))
Ali A
+4  A: 

And in this context it can also be good to remember that strings are also iterable.

>>> a = [1, 2]
>>> a
[1, 2]
>>> a.extend('hey')
>>> a
[1, 2, 'h', 'e', 'y']
+1 Very good tip. As a beginner, you can easily get this wrong.
Helper Method