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

How to round values in a list containing tuples

I have a list, which has 2 more lists within it and both of the lists each have 2 tuples in them.

lst = [
  [('Jade', 0.9877607), ('Tom', 0.5728347)],
  [('Jackson', 0.6892309), ('Hazel', 0.6837777)]
]

I want to round all 4 float values to 2 d.p. Would I have to turn each tuple into a list and then change it or is there an easier way to do it?

Thanks!

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 :

Since tuples are immutable, you cannot modify them in-place. You’ll need to create a new list based on the current list.

This is very simple to do using a list comprehension:

lst = [
    [('Jade', 0.9877607), ('Tom', 0.5728347)], 
    [('Jackson', 0.6892309), ('Hazel', 0.6837777)],
]

new_list = [
    [(name, round(value, 2)) for (name, value) in sublist]  
    for sublist in lst
]
print(new_list)

# Output:

# [
#    [('Jade', 0.99), ('Tom', 0.57)],
#    [('Jackson', 0.69), ('Hazel', 0.68)]
# ]
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