What is the difference between the list methods append
and extend
?
views:
2176answers:
5
+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
2008-10-31 05:57:32
+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
2008-10-31 05:57:37
Note, `extend` doesn't just concatenate lists, it extends a list with an arbitrary iterable.
Mike Graham
2010-03-19 00:16:14
+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
2008-10-31 06:02:25
+5
A:
Good answers, but don't forget, any iterable will do for extend (not just list):
l.extend(xrange(5))
Ali A
2008-10-31 09:03:22
+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']