Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to simultaneously add two lists to a list?

Let's say I have a list

l1 = []

another list

l2 = ['a','b']

and two variables

u = 1
z = 2

Now I would like to add l2 to l1 and the two variables as a list to l1 as well. One can do it in two steps using append:

l1.append(l2)
l1.append(list((u,z)))

which gives me the desired output

[['a', 'b'], [1, 0]]

But something like

l1.append(l2, list((u,z)))

does not work. Is there a way to get the same output I obtain for the two steps in a nice oneliner i.e. can one simultaneously append a list by two lists?

like image 949
Cleb Avatar asked Dec 03 '25 23:12

Cleb


1 Answers

l1.extend([l2, [u,z]])

append can only add one element to a list. extend takes a list and adds all the elements in it to other list.

like image 72
Ionut Hulub Avatar answered Dec 08 '25 15:12

Ionut Hulub



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!