# Introduction

The Cartesian product of two lists is calculated by iterating over every element in the first and second list and outputting points. This is not a very good definition, so here are some examples: the Cartesian product of [1, 2] and [3, 4] is [(1, 3), (1, 4), (2, 3), (2, 4)]. The product of [1] and [2] is [(1, 2)]. However, no one said you could only use two lists. The product of [1, 2], [3, 4], and [5, 6] is [(1, 3, 5), (1, 4, 5), (1, 3, 6), (1, 4, 6), (2, 3, 5), (2, 4, 5), (2, 3, 6), (2, 4, 6)].

# Challenge

Given a number of lists, your program must output the Cartesian product of the lists given.

• You can assume that there will always be more than 1 list, and that each list will have the same length. No list will ever be empty. If your language has no method of stdin, you may take input from command line arguments or a variable.
• Your program must output the Cartesian product of all the input lists. If your language has no stdout, you may store output in a variable or as a return value. The output should be a list of lists, or any other iterable type.

# Example I/O

Input: [1, 2] [3, 4]
Output: [(1, 3), (1, 4), (2, 3), (2, 4)]

Input: [1, 2] [3, 4] [5, 6]
Output: [(1, 3, 5), (1, 4, 5), (1, 3, 6), (1, 4, 6), (2, 3, 5), (2, 4, 5), (2, 3, 6), (2, 4, 6)]

Input: [1, 2, 3] [4, 5, 6]
Output: [(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]

# Rules

This is so shortest answer in bytes wins!

• boring answer: itertools.product in python Nov 16, 2019 at 17:54
• Nov 16, 2019 at 23:13
• If your language has no method of stdin, you may take input from command line arguments or a variable I suggest you allow command-line inputs without any condition. See here Nov 17, 2019 at 3:12
• Does order matter among the output lists?
– xnor
Nov 17, 2019 at 5:45
• No, the format described is not mandatory @KevinCruijssen Nov 18, 2019 at 22:09

# J, 1 byte

Courtesy of ngn

{


Try it online!

'tis called Catalogue

• You beat me to it :). I think ,@{ would be more fair though, since the output of naked { doesn't have a uniform structure (ie, it depends on the inputs). Nov 16, 2019 at 19:40
Nov 16, 2019 at 19:45
• results not seem list deep 1 of element of input
– user58988
Nov 17, 2019 at 7:04
• @RosLuP It is. J's Try it online! L. is APL's ≡.
Nov 17, 2019 at 7:24

mapM id


Try it online!

## Built-in, 8 bytes

sequence


Try it online!

## Less boring, 33 bytes

f[]=[[]]
f(h:t)=[i:j|i<-h,j<-f t]


Try it online!

foldr((<*>).map(:))[[]]


Try it online!

Without using mapM or sequence or the like.

# Python 3, 56 bytes

def f(M,*l):M and[f(M[1:],*l,x)for x in M[0]]or print(l)


Try it online!

No itertools. This is one of those weird functions that prints. Thanks to Unrelated String for -2 bytes with def.

• Since the return value doesn't matter, you can shave two bytes off by using def: Try it online! Nov 17, 2019 at 6:09
• @ChasBrown I don't think that's allowed, it nests the output a lot. And unfortunately Python doesn't do iterable unpacking in comprehensions.
– xnor
Nov 17, 2019 at 9:11
• @xnor : quite right! Carry on... Nov 17, 2019 at 9:12

# Python 2, 60 59 bytes

f=lambda A,*x:[[v]+u for v in A for u in x and f(*x)or[[]]]


Try it online!

1 byte thx to ovs.

Look Ma! No itertools!

• 59 bytes
– ovs
Nov 17, 2019 at 13:43

# Japt-R, 2 bytes

A simple reduction by Cartesian product.

rï


Try it

• Lol! Congrats! You preceded me by 12 minutes ! Anyway I'm really proud of .. I immediately thought about that solution Nov 16, 2019 at 21:34
• Ha, I spent 15 minutes looking through Japt docs and couldn't find this again. Lol Nov 17, 2019 at 14:32
• @KevinCruijssen, here it is "pretty printed": petershaggynoble.github.io/Japt-Interpreter/… Nov 18, 2019 at 12:39
• OP stated the output-format is indeed flexible, and those outputs are allowed. Nov 19, 2019 at 7:08
• Thanks, @KevinCruijssen. I've updated to Japt -R anyway. Nov 19, 2019 at 10:43

# Jelly, 4 2 bytes

Œp


Try it online!

Output is "pretty printed" in the TIO link

# Brachylog, 1 byte

ẋ


Try it online!

A slightly less boring generator solution:

# Brachylog, 2 bytes

∋ᵐ


Try it online!

• A careful reading of the rules suggests that function submissions are only allowed to output through return values if printing is impossible, so if that's actually enforced, +1 byte to the first for w, and +2 to the second for ẉ⊥. Nov 18, 2019 at 21:25

# K (oK), 31 15 bytes

{x@'/:+!(#:)'x}


Try it online!

• How are you finding K compared with J? What have you been using to learn it? Nov 17, 2019 at 16:36
• @Jonah I can't compare them directly. K lacks J's math capabilities, but works on heterogeneous lists. It is much more compact and I like it very much even I have only sctratched the surface. I started learning from the oK Manual. On several occasions ngn helped me in thr k tree. He also supplied almost all my previos k submissions with golfing tips. Nov 17, 2019 at 19:31

# Perl 6, 8 4 bytes

&[X]


Try it online!

Simple reduce by cross product. It would be nice if I could return the meta-operator by itself, but I've never figured out how to do that. Turns out it works for cross product?

• &[X] seems to work in this case. Nov 17, 2019 at 16:52
• @nwellnhof What? But &[+] doesn't work? I don't understand when it does and doesn't work
– Jo King
Nov 17, 2019 at 20:43
• Seems to be an implementation detail of the infix operators. Some infix operators accept more than two args but it's not a requirement. Nov 17, 2019 at 22:03

# Ruby, 20 bytes

->i,*j{i.product *j}


Try it online!

# Retina, 5439 32 bytes

This took really long to write (as I tried to golf it too) (unsurprisingly, all the golfing ideas only appeared after I finally posted this). Takes input as a list of strings of alphanumeric characters and underscores (whatever \w matches in your universe), each preceded by a semicolon (I assume characters are as acceptable in Retina as numbers are in everything else; in fact, the challenge never actually specified numbers). Outputs the list of the resulting strings, each preceded by a comma.

^
,
+w,(\w*)[^;]*;\w*(\w)
,$1$2


Explanation:

^                       match the beginning of the string
+w,(\w*)[^;]*;\w*(\w)  solve the rest of the problem
,$1$2                   replace with a comma, group 1 and group 2


The third and fourth lines are in a convergence loop (run until no change) (declared by the +). The regular expression in the 3rd line works on lines like , ac, bc, ad, bd;ef;gh and matches all substrings starting at a comma and ending at a character after the first semicolon, where the group 1 is the string after the comma and group 2 is the last character.

Try it online!

# Python 3 (Cython), 4644 31 bytes

__import__('itertools').product


Try it online!

This doesn't need more explanation, right?

(-13 bytes thanks to Jo King; -2 bytes thanks to caird coinheringaahing)

• Welcome to the site! Unnamed lambdas are perfectly acceptable here, so you can remove the f= to save two bytes. Nov 18, 2019 at 13:58
• @cairdcoinheringaahing Thank you! I have removed the f=. I'm not sure how to make TIO count this as 44 bytes though ... Nov 18, 2019 at 14:03
• This should work Nov 18, 2019 at 14:03
• @cairdcoinheringaahing Thanks! Didn't know that the backslash works here. Nov 19, 2019 at 11:33

# Zsh, 30 bytes

for l;a=($^a\${^${=l}}) <<<$a


Try it online!

Split = and cartesian product ^ for each element. Our base case adds an extra space, which cleanly separates our output lists.

# R, 54 47 bytes

f=function(x)split(j<-expand.grid(x),1:nrow(j))


Try it online!

If you consider data.frame rows iterable:

# R, 27 bytes

f=function(x)expand.grid(x)


Try it online!

• You don't need to include the f= in the byte count here, and can include it in the header: Example . Also, as expand.grid is a built-in, this is basically 11 bytes as expand.grid returns the function. I think we've scored them as such in the past, though am happy to be corrected by someone with more intimate knowledge of practice. Nov 18, 2019 at 11:57

# 05AB1E, 3 bytes

.»â


Outputs [[a,b],[c,d],[d,e]] in the format [[[a,c],d], [[a,c],e], ...]. To output in the format [[a,[c,d]], [a,[c,e]], ...], replace the » with «.

Explanation:

.»   # (Left-)reduce by (or right-reduce with .«):
â  #  Taking the cartesian product of the two lists
# (after which the resulting list is output implicitly)



# Husk, 1 byte

Π


Try it online! Π takes the Cartesian product of a list of lists.

# Wolfram Language (Mathematica), 6 bytes

Tuples


Try it online!

# JavaScript (Node.js), 52 bytes

Returns a list of lists.

f=([a,...b],o=[])=>a?a.flatMap(x=>f(b,[...o,x])):[o]


Try it online!

# JavaScript (V8), 52 bytes

Prints the results.

f=([a,...b],o)=>a?a.map(x=>f(b,o?o+[,x]:x)):print(o)


Try it online!

# Erlang, 57 bytes

c([]) -> [[]];
c([H|T]) -> [[X|Y] || X <- H, Y <- c(T)].


# Japt, 2 bytes

rï


Try it

Reduces input by combination with initial value of 1st element


Duplicate of @Shaggy answer, I was solving this while he just posted the same solution. I hope I can leave my answer too because it's awesome

# Charcoal, 22 bytes

ＩＥΠＥθＬιＥθ§λ÷ιΠ∨Ｅ…θμＬν¹


Try it online! Link is to verbose version of code. Explanation:

    θ                   Input list
Ｅ                    Map over elements
ι                 Current element
Ｌ                  Length
Π                     Product
Ｅ                      Map over implicit range
θ               Input list
Ｅ                Map over elements
λ             Current element
§              Cyclically indexed by
ι           Outer index
÷            Integer divide
θ      Input list
…       Truncated to length
μ     Inner index
Ｅ        Map over elements
ν   Current element
Ｌ    Length
∨      ¹  Replace empty list with literal 1
Π          Product
Ｉ                       Cast to string
Implicitly print double-spaced on separate lines


## Julia 1.0, 34 bytes

No imports used, iterators in Base has this. It actually makes a lazy form of this, but to print them all it will collect each one.

println.(Iterators.product(l...))


where l is the list of lists.

# APL(NARS), chars 11, bytes 22

{,↑(∘.,)/⍵}


test for product of sets:

  f←{,↑(∘.,)/⍵}
⎕fmt (1 2)(3 4)
┌2────────────┐
│┌2───┐ ┌2───┐│
││ 1 2│ │ 3 4││
│└~───┘ └~───┘2
└∊────────────┘
⎕fmt f (1 2)(3 4)
┌4──────────────────────────┐
│┌2───┐ ┌2───┐ ┌2───┐ ┌2───┐│
││ 1 3│ │ 1 4│ │ 2 3│ │ 2 4││
│└~───┘ └~───┘ └~───┘ └~───┘2
└∊──────────────────────────┘
⎕fmt f (1 2)(3 4)(5 6)
┌8──────────────────────────────────────────────────────────────────────┐
│┌3─────┐ ┌3─────┐ ┌3─────┐ ┌3─────┐ ┌3─────┐ ┌3─────┐ ┌3─────┐ ┌3─────┐│
││ 1 3 5│ │ 1 3 6│ │ 1 4 5│ │ 1 4 6│ │ 2 3 5│ │ 2 3 6│ │ 2 4 5│ │ 2 4 6││
│└~─────┘ └~─────┘ └~─────┘ └~─────┘ └~─────┘ └~─────┘ └~─────┘ └~─────┘2
└∊──────────────────────────────────────────────────────────────────────┘
≢f (1 2)(3 4)(5 6)
8
f (⍳3)(4 5 6)
1 4  1 5  1 6  2 4  2 5  2 6  3 4  3 5  3 6

⎕fmt f (4 5 6)
┌1───────┐
│┌3─────┐│
││ 4 5 6││
│└~─────┘2
└∊───────┘


# Python 3.8, 136 bytes

import re
from itertools import*
print(list(product(*[[int(i) for i in i.split(', ')] for i in re.findall(r'$([0-9, ]+)$',input())])))


Try it online!

• You don't have to do any of the string processing. You could just take input as a list of lists: "Given a number of lists" Nov 16, 2019 at 18:03
• The heart of this answer is just itertools.product too.
– qwr
Nov 17, 2019 at 6:13