0

lets say I have one list ['A','B','C']

and the second [1,2]

I want to create a new list [(A,1), (A,2), (B,1)...]

Obviously it can be trivially done using a for loop like this:

a = ['A','B','C']
b = [1,2]
c = []
for x in a:
    for y in b:
        c.append((x,y))

c
[('A', 1), ('A', 2), ('B', 1), ('B', 2), ('C', 1), ('C', 2)]

but how can I do it using the [x for x in...] syntax ?

5 Answers 5

4

You need the Cartesian Product of the two lists:

>>> from itertools import product

>>> list(product(a, b))
[('A', 1), ('A', 2), ('B', 1), ('B', 2), ('C', 1), ('C', 2)]

Unlike an explicit list comprehension, this is trivially scalable to any number of input iterables. See here for details.

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

Comments

3

Take a look at itertools.product:


>>> from itertools import product
>>> a = [ 'A', 'B', 'C' ]
>>> b = [ 1, 2]
>>> [ x for x in product(a, b) ]
[('A', 1), ('A', 2), ('B', 1), ('B', 2), ('C', 1), ('C', 2)]

Comments

2

Using python lists:

[(i, j) for i in a for j in b]

Using a module:

from itertools import product

list(product(a, b))

Comments

2

[x for x in...] syntax has name and it called list comprehension, you can write your loops between [ and ] and put inner most before your loops.

[(x, y) for x in a for y in b]

Comments

1

In your case the list comprehensions version could be:

>>> [(x, y) for x in "ABC" for y in [1,2]]
[('A', 1), ('A', 2), ('B', 1), ('B', 2), ('C', 1), ('C', 2)]

Note that the order matters, that is for a fixed x='A' the possible values of y are iterated first.

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.