Beginner Prog
Beginner Prog

Reputation: 39

python, list and generator concatenation

I want to join in a list, a generator and a list. For example at Step 1 , I have an empty list

A = []

and generator B which gives me the combinations of a list L:

B = combinations(list(L[0]), 2), 

which give me for example B=[(1,2), (1,3), (1,4)]

I want to have a list A = [(1,2), (1,3), (1,4)]

Step 2:

A = [(1,2), (1,3), (1,4)]
B = combinations(list(L[1]), 2)= [(2,4),(4,5)]

I want now my A to be:

A = A + B = [ (1,2), (1,3), (1,4), (2,4),(4,5) ]

How is that possible ?

Upvotes: 0

Views: 745

Answers (2)

DenverCoder1
DenverCoder1

Reputation: 2501

You can use the Python extend() method:

A = [(1,2), (1,3), (1,4)]
B = [(2,4),(4,5)]

A.extend(B)

Now A has the value [ (1,2), (1,3), (1,4), (2,4), (4,5) ]

This also seems to work fine:

A = [(1,2), (1,3), (1,4)]
B = [(2,4),(4,5)]

A = A + B

Upvotes: 1

chepner
chepner

Reputation: 531325

Use itertools.chain

from itertools import chain


A = list(chain(A, B))

If you want to modify A in place, just use extend (whose argument can be any iterable value):

A.extend(B)

Upvotes: 3

Related Questions