Created
September 4, 2012 21:52
-
-
Save benjamingeiger/3627064 to your computer and use it in GitHub Desktop.
Cartesian product of lists in Python.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can you do it iteratively without list comprehension?