3

How would I accomplish the following in python:

first = ['John', 'David', 'Sarah']
last = ['Smith', 'Jones']

combined = ['John Smith', 'John Jones', 'David Smith', 'David Jones', 'Sarah Smith', 'Sarah Jones']

Is there a method to combine all permutations?

David542
  • 104,438
  • 178
  • 489
  • 842

4 Answers4

11

itertools.product

import itertools
combined = [f + ' ' + l for f, l in itertools.product(first, last)]
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
7

Not sure if there is a more elegant solution, but this should work:

[x + " " + y for x in first for y in last]

happydave
  • 7,127
  • 1
  • 26
  • 25
4

product from itertools will do the trick.

product(first, last)

will give return a generator with all possible combinations of first and last. After that, all you need to do is concatenate the first and last names. You can do this in one expression:

combined = [" ".join(pair) for pair in product(first, last)]

It's also possible to do this with string concatenation:

combined = [pair[0] + " " + pair[1] for pair in product(first, last)]

This method is slower though, as the concatenation done in the interpreter. It's always recommended to use the "".join() method as this code is executed in C.

Joel Cornett
  • 24,192
  • 9
  • 66
  • 88
0

I am not aware of any python utility method for this, however following will achieve the same:

def permutations(first, second):
  result = []
  for i in range(len(first)):
    for j in range(len(second)):
      result.append(first[i] + ' ' + second[j])
  return result 
18bytes
  • 5,951
  • 7
  • 42
  • 69
  • 1
    Your Python knowledge is a little out of date, you need a refresher. Read and learn from the other posts, esp. the one from Joel Cornett. itertools.product handles the for-loop nesting, and list comprehensions are better than explicit appending as your code does. – PaulMcG Apr 29 '12 at 06:18
  • Thanks for the suggestion. I realized the same after reading other answers, i have gone throgh the itertools and list comprehensions now. – 18bytes May 02 '12 at 04:44