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!
>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)]
# ]