Skip to content Skip to sidebar Skip to footer

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',

Solution 1:

itertools.product

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

Solution 2:

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

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

Solution 3:

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.

Solution 4:

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

def permutations(first, second):
  result= []
  for i inrange(len(first)):
    for j inrange(len(second)):
      result.append(first[i] +' '+second[j])
  returnresult

Post a Comment for "Python Permutation"