Skip to content

Instantly share code, notes, and snippets.

@gideondsouza
Created September 6, 2013 07:35
Show Gist options
  • Save gideondsouza/6460685 to your computer and use it in GitHub Desktop.
Save gideondsouza/6460685 to your computer and use it in GitHub Desktop.
Python Comprehensions 3
>>>
>>> L = [1,2,3,4,5] #define a list 1 to 5
>>> [(x,y) for x in L for y in L] # we have two fors running over the list
#this gives all the 25 non-unique combinations
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5),
(3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5),
(5, 1), (5, 2), (5, 3), (5, 4), (5, 5)]
#need unque combinations. No problem! Add an if in the end.
>>> [(x,y) for x in L for y in L if x!=y]
[(1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2),
(3, 4), (3, 5), (4, 1), (4, 2), (4, 3), (4, 5), (5, 1), (5, 2), (5, 3), (5, 4)]
>>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment