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?

1
  • You could code a permutation generator yourself in any* language. Commented Apr 29, 2012 at 3:00

4 Answers 4

11

itertools.product

import itertools
combined = [f + ' ' + l for f, l in itertools.product(first, last)]
Sign up to request clarification or add additional context in comments.

Comments

7

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

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

Comments

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.

Comments

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 

2 Comments

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.
Thanks for the suggestion. I realized the same after reading other answers, i have gone throgh the itertools and list comprehensions now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.