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?

1
  • 2
    my_list + ['a','b'] Commented Mar 19, 2014 at 4:59

3 Answers 3

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'))
Sign up to request clarification or add additional context in comments.

Comments

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'

Comments

1
l = []
l.extend([1,2,3,4,5])

There is a method for your purpose.

1 Comment

oops, another person gave the same answer at the almost same time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.