Showing posts with label list comprehension. Show all posts
Showing posts with label list comprehension. Show all posts

Sunday, February 12, 2012

Easy Permutation Calculation in Python

I was recently doing some Python programming, and had to compute all possible combinations of items from two separate lists. At first, I thought, I'll just do it this way:

list1 = ['a', 'b', 'c']
list2 = ['x', 'y', 'z']
for i in list1:
    for j in list2:
        print i, j
a x
a y
a z
b x
b y
b z
c x
c y
c z

However, my loop body was something that was a little more complicated than a print, and couldn't be done well inside of a loop like that. And besides - this is Python we're talking about. Surely there is a better way!

Well, there is - and don't call me Shirley. Details coming up after the break!