Say I have a list
l = [1,2,3]
and I want to sum each item in the list with every other item in the list. I could do this:
x = [(a, b) for a in l for b in l]
y = [(a + b) for a in l for b in l]
x = [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
y = [2, 3, 4, 3, 4, 5, 4, 5, 6]
Is assigning two variables (a
and b
) to items in the same list (l
) the best way to access and perform operations on those items? Is there a better way to do this?
I've looked at list methods and functions, and couldn't find any.
UPDATE
Many people recommended the itertools product function so I thought I'd include timings before I mark as answered:
mysetup = """
from itertools import product
l = [10, 15, 3, 7]
k = 17
"""
mycode = """
[i for i in product(l, repeat=2)]
"""
t = timeit.timeit(setup=mysetup, stmt=mycode, number=100000)
# 0.1505305
mysetup2 = """
l = [10, 15, 3, 7]
k = 17
"""
mycode2 = """
[(a, b) for a in l for b in l]
"""
t1 = timeit.timeit(setup=mysetup2, stmt=mycode2, number=100000)
# 0.1432976
You can assign the same value to multiple variables by using = consecutively. This is useful, for example, when initializing multiple variables to the same value. It is also possible to assign another value into one after assigning the same value.
Given above is the mechanism for assigning just variables in Python but it is possible to assign multiple variables at the same time.
Python provides built in method
from itertools import product
l = [1,2,3]
Then generate the sum using list comprehension in a single step to be more efficent
result= [sum(i) for i in product(l, repeat= 2) ]
#result=[2, 3, 4, 3, 4, 5, 4, 5, 6]
Here's an itertools
based approach:
from operator import add
from itertools import product, starmap
l = [1,2,3]
list(starmap(add, product(l, repeat=2)))
# [2, 3, 4, 3, 4, 5, 4, 5, 6]
Let's check the timings:
l = list(range(1000))
%timeit list(map(sum, product(l, repeat=2)))
# 187 ms ± 14.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit [sum(combination) for combination in combinations_with_replacement(l, 2)]
# 123 ms ± 4.32 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
list(starmap(add, product(l, repeat=2)))
# 102 ms ± 4.11 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
Try this, itertools.product
>>> from itertools import product
>>> l = [1,2,3]
>>> [sum(combination) for combination in list(product(l, repeat = 2))]
[2, 3, 4, 3, 4, 5, 4, 5, 6]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With