0

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?

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
doniyor
  • 36,596
  • 57
  • 175
  • 260

3 Answers3

3

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'))
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
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'
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
1
l = []
l.extend([1,2,3,4,5])

There is a method for your purpose.

crzyonez777
  • 1,789
  • 4
  • 18
  • 27