Skip to content

Instantly share code, notes, and snippets.

@benjamingeiger
Created September 4, 2012 21:52
Show Gist options
  • Select an option

  • Save benjamingeiger/3627064 to your computer and use it in GitHub Desktop.

Select an option

Save benjamingeiger/3627064 to your computer and use it in GitHub Desktop.
Cartesian product of lists in Python.
def cartesian (lists):
if lists == []: return [()]
return [x + (y,) for x in cartesian(lists[:-1]) for y in lists[-1]]
print cartesian([[1, 2, 3], [2, 4, 6], [3, 6, 9]])
@toxintractor
Copy link
Copy Markdown

Can you do it iteratively without list comprehension?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment