Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List multiplication

I have a list L = [a, b, c] and I want to generate a list of tuples :

[(a,a), (a,b), (a,c), (b,a), (b,b), (b,c)...] 

I tried doing L * L but it didn't work. Can someone tell me how to get this in python.

like image 321
Schitti Avatar asked Jan 30 '10 23:01

Schitti


People also ask

Can we multiply a list?

We can simply get the product of two lists using for loop. Through for loop, we can iterate through the list. Similarly, with every iteration, we can multiply the elements from both lists. For this purpose, we can use Zip Function.

Can you multiply a list in Python?

Lists and strings have a lot in common. They are both sequences and, like pythons, they get longer as you feed them. Like a string, we can concatenate and multiply a Python list.

How do you multiply a constant in a list Python?

Method #2 : Using map() + operator.mul This is similar to the above function but uses the operator. mul to multiply each element to other element from the other list of K formed before applying the map function.


4 Answers

You can do it with a list comprehension:

[ (x,y) for x in L for y in L]

edit

You can also use itertools.product as others have suggested, but only if you are using 2.6 onwards. The list comprehension will work will all versions of Python from 2.0. If you do use itertools.product bear in mind that it returns a generator instead of a list, so you may need to convert it (depending on what you want to do with it).

like image 83
Dave Kirby Avatar answered Oct 05 '22 22:10

Dave Kirby


The itertools module contains a number of helpful functions for this sort of thing. It looks like you may be looking for product:

>>> import itertools
>>> L = [1,2,3]
>>> itertools.product(L,L)
<itertools.product object at 0x83788>
>>> list(_)
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
like image 23
Greg Hewgill Avatar answered Oct 05 '22 23:10

Greg Hewgill


Take a look at the itertools module, which provides a product member.

L =[1,2,3]

import itertools
res = list(itertools.product(L,L))
print(res)

Gives:

[(1,1),(1,2),(1,3),(2,1), ....  and so on]
like image 27
Alexander Gessler Avatar answered Oct 06 '22 00:10

Alexander Gessler


Two main alternatives:

>>> L = ['a', 'b', 'c']
>>> import itertools
>>> list(itertools.product(L, L))
[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]
>>> [(one, two) for one in L for two in L]
[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]
>>> 

the former one needs Python 2.6 or better -- the latter works in just about any Python version you might be tied to.

like image 27
Alex Martelli Avatar answered Oct 06 '22 00:10

Alex Martelli