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

From a list of tuples add one to each tuple element using list comprehension

I have a list and I would like to get a new list such that each tuple in position 0 has 1 added to it. I can build a new list of tuples using loops but I want to understand how to do this with list comprehensions.
What I have:

in_list = [(0, 1), (1, 1), (2, 1), (3, 3), (4, 4)]

What I want:

in_list = [(1, 1), (2, 1), (3, 1), (4, 3), (5, 4)]

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

>Solution :

Tuple is immutable type, so to increase the value at position 0, construct new tuple:

in_list = [(0, 1), (1, 1), (2, 1), (3, 3), (4, 4)]


in_list = [(a + 1, b) for a, b in in_list]
print(in_list)

Prints:

[(1, 1), (2, 1), (3, 1), (4, 3), (5, 4)]
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