Can any python module support listing 2 lists and do cross-multiplication?

I often write below snippets in daily work,

res = []
a = ["A","B","C","D"]
b = [1,2,3,4]
for _a in a:
    for _b in b:
        res.append((_a,_b))
# or be more simple 
#[(_a,_b) for _a in a for _b in b]

[('A', 1),
 ('A', 2),
 ('A', 3),
 ('A', 4),
 ('B', 1),
 ('B', 2),
 ('B', 3),
 ('B', 4),
 ('C', 1),
 ('C', 2),
 ('C', 3),
 ('C', 4),
 ('D', 1),
 ('D', 2),
 ('D', 3),
 ('D', 4)]

Can i find out

  • if there is any special term in the computer field for this kind of action?
  • if there is a way, for example. python module can do the job? For example, do I have 20 lists that need a list of all combinations? can itertools do this?

thank

+3
source share
2 answers

itertools.product - this is exactly what you need:

>>> list(itertools.product("ABCD", "1234"))
[('A', '1'), ('A', '2'), ('A', '3'), ('A', '4'), ('B', '1'),
('B', '2'), ('B', '3'), ('B', '4'), ('C', '1'), ('C', '2'),
('C', '3'), ('C', '4'), ('D', '1'), ('D', '2'), ('D', '3'),
('D', '4')]
+3
source

You are looking for itertools.product().

res = list(itertools.product(a, b))
+2
source

All Articles