Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Multiply a list of tuples by a constant

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading