2

I am trying to concatenate two lists, one with just one element, by doing this:

print([6].append([1,1,0,0,0]))

However, Python returns None. What am I doing wrong?

4 Answers 4

10

Use the + operator

>>> [6] + [1,1,0,0,0]
[6, 1, 1, 0, 0, 0]

What you were attempting to do, is append a list onto another list, which would result in

>>> [6].append([1,1,0,0,0])
[6, [1,1,0,0,0]]

Why you are seeing None returned, is because .append is destructive, modifying the original list, and returning None. It does not return the list that you're appending to. So your list is being modified, but you're printing the output of the function .append.

Sign up to request clarification or add additional context in comments.

Comments

5

For list concatenation you have two options:

newlist = list1 + list2

list1.extend(list2)

1 Comment

The latter modifies the list, the former creates a new one. That's a significant difference in several cases.
2

use a list first (unless you really do not want to use your data in future )

>>> a=[6]
>>> a.append([1,1,0,0,0])
>>> a
[6, [1, 1, 0, 0, 0]]

another way is to use extend() instead of append()

>>> a=[6]
>>> a.extend([1,1,0,0,0])
>>> a
[6, 1, 1, 0, 0, 0]

1 Comment

I like the mention of extend as alternative to summing, but I downvoted this answer because the result of extend is not the same as append, although in your answer you pretend like it is a different way to get the same result...
0
l1 = [6]
l2 = [1, 1, 0, 0, 0]
l1.extend(l2)
print l1
[6, 1, 1, 0, 0, 0]

Comments

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.