Cleb
Cleb

Reputation: 25997

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?

Upvotes: 3

Views: 385

Answers (4)

Rahul Gupta
Rahul Gupta

Reputation: 47846

You can use any of the following methods:

Method 1 :

>>> l1.extend([l2, [u,z]])
>>> l1
[['a', 'b'], [1, 2]]

append: Appends object at end
extend: Extends list by appending elements from the iterable

Method 2 :

>>> l1 += [l2] + [[u, z]]
>>> l1
[['a', 'b'], [1, 2]]

Upvotes: 1

Shruti Srivastava
Shruti Srivastava

Reputation: 398

This is simple by creating a generator

import itertools
for item in itertools.chain(listone, listtwo):
# do what you want to do with this merged list

Upvotes: 1

Avión
Avión

Reputation: 8386

You can use extend as follows:

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

Or just:

l1 + [l2] + [[u,z]]

Upvotes: 3

Ionut Hulub
Ionut Hulub

Reputation: 6326

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.

Upvotes: 5

Related Questions