Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem concatenating Python list

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?

like image 344
wrongusername Avatar asked Dec 08 '25 01:12

wrongusername


2 Answers

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.

like image 198
Josh Smeaton Avatar answered Dec 10 '25 13:12

Josh Smeaton


For list concatenation you have two options:

newlist = list1 + list2

list1.extend(list2)
like image 39
joaquin Avatar answered Dec 10 '25 14:12

joaquin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!