Reputation: 37924
I want to append multiple elements to my list at once. I tried this:
>>> l = []
>>> l.append('a')
>>> l
['a']
>>> l.append('b').append('c')
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
l.append('b').append('c')
AttributeError: 'NoneType' object has no attribute 'append'
>>>
How can I append 'b'
and 'c'
at once?
Upvotes: 0
Views: 10134
Reputation: 251136
Use list.extend
:
>>> l = []
>>> l.extend(('a', 'b'))
>>> l
['a', 'b']
Note that similar to list.append
, list.extend
also modifies the list in-place and returns None
, so it is not possible to chain these method calls.
But when it comes to string, their methods return a new string. So, we can chain methods call on them:
>>> s = 'foobar'
>>> s.replace('o', '^').replace('a', '*').upper()
'F^^B*R'
Upvotes: 2
Reputation: 1807
l = []
l.extend([1,2,3,4,5])
There is a method for your purpose.
Upvotes: 1
Reputation: 34176
The method append()
works in place. In other words, it modifies the list, and doesn't return a new one.
So, if l.append('b')
doesn't return anything (in fact it returns None
), you can't do:
l.append('b').append('c')
because it will be equivalent to
None.append('c')
Answering the question: how can I append 'b' and 'c' at once?
You can use extend()
in the following way:
l.extend(('b', 'c'))
Upvotes: 3