I have a list of tuples as follows:
[ (-100,-100), (-100,0), (-50,-100), (-50,-50), (-50,0), (-50,50), (-50,100), (0,-100), (0,-50), (0,0), (0,50), (0,100), (50,-100), (50,50), (50,0), (50,50), (50,100), (100,100), (100,0)]
How can I multiply each element of each tuple by a constant C, in a Pythonic way, retaining the original order and structure of the list of tuples?
In other words, I should end up with:
[ (-C*100, -C*100), (-C*100, 0), ... , (C*100, C*100), (C*100, 0) ]
>Solution :
A list comprehension should do nicely. If we don’t know if all of the tuples are the same length, we can iterate over them with a generator expression, and then convert that to a tuple.
data = [ (-100,-100), (-100,0), (-50,-100), (-50,-50), (-50,0), (-50,50), (-50,100), (0,-100), (0,-50), (0,0), (0,50), (0,100), (50,-100), (50,50), (50,0), (50,50), (50,100), (100,100), (100,0)]
multiplied = [tuple(x * constant for x in tpl) for tpl in data]