David542
David542

Reputation: 110203

Python permutation

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?

Upvotes: 3

Views: 1305

Answers (4)

Joel Cornett
Joel Cornett

Reputation: 24788

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.

Upvotes: 4

18bytes
18bytes

Reputation: 6029

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 

Upvotes: 0

happydave
happydave

Reputation: 7187

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

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

Upvotes: 7

Matthew Flaschen
Matthew Flaschen

Reputation: 284826

itertools.product

import itertools
combined = [f + ' ' + l for f, l in itertools.product(first, last)]

Upvotes: 11

Related Questions