0

I would like to multiply 2 lists of strings in python but not by values. Like this example :

elem1 = ['a', 'b']
elem2 = ['c', 'd']
final = magic_function(elem1, elem2)
>> final = [
    ['a','c'],
    ['a','d'],
    ['b','c'],
    ['b','d']
]

I tried looking at the numpy package but I can't find anything which is not multiply by scalar

5
  • Typo : elem2 = ['a', 'b']? Commented Sep 16, 2017 at 18:09
  • 2
    You should have a look at itertools, not numpy. Commented Sep 16, 2017 at 18:10
  • Also, you need to understand the term multiply Commented Sep 16, 2017 at 18:14
  • 5
    Possible duplicate of Get the cartesian product of a series of lists? Commented Sep 16, 2017 at 18:24
  • Yup, I have edited the typo. I will look at all your solutions tomorrow, thanks for the answers guys ! Commented Sep 16, 2017 at 22:26

3 Answers 3

1

This can be done with a simple list comprehension final = [[v1, v2] for v1 in elem1 for v2 in elem2].

Sign up to request clarification or add additional context in comments.

Comments

1
import itertools
list(itertools.product(elem1,elem2))

By using itertools you can have the all possible combination of two lists. But it will generate list of tuples.

Comments

0

Have a look at itertools

Assuming

elem1 = ['a', 'b']
elem2 = ['c', 'd']

Using list comprehension:

[(a, b) for a in elem1 for b in elem2]

Result: [[('a', 'c'), ('b', 'd')], [('a', 'd'), ('b', 'c')]]

1 Comment

OP's example doesn't look like permutations at all.

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.