Python List Append Multiple Elements
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') Tra
Solution 1:
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'))
Solution 2:
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'
Solution 3:
l = []
l.extend([1,2,3,4,5])
There is a method for your purpose.
Post a Comment for "Python List Append Multiple Elements"