Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify each element of a tuple in a list of tuples

I have a list of tuples:

my_list = 
 [(0.12497007846832275, 0.37186527252197266, 0.9681450128555298, 0.5542989373207092), 
 (0.18757864832878113, 0.6171307563781738, 0.8482183218002319, 0.8088157176971436), 
 (0.06923380494117737, 0.2164008915424347, 0.991775393486023, 0.41364166140556335)]

I want to multiply each value to 100 and then reassign them in the same order. But doing below, it throws error:

for i in range(len(my_list)):
    for j in range(4):
        my_list[i][j] = 100 * my_list[i][j]

TypeError: 'tuple' object does not support item assignment

How can I modify these values and save them in their places?

like image 211
S Andrew Avatar asked Jan 28 '23 03:01

S Andrew


1 Answers

If you read the docs, you will learn that tuples are immutable (unlike lists), so you cannot change values of tuples.

Use a list-comprehension:

my_list = [(0.12497007846832275, 0.37186527252197266, 0.9681450128555298, 0.5542989373207092), 
           (0.18757864832878113, 0.6171307563781738, 0.8482183218002319, 0.8088157176971436), 
           (0.06923380494117737, 0.2164008915424347, 0.991775393486023, 0.41364166140556335)]

my_list = [tuple(y * 100 for y in x ) for x in my_list]
# [(12.497007846832275, 37.186527252197266, 96.814501285552979, 55.429893732070923),   
#  (18.757864832878113, 61.713075637817383, 84.821832180023193, 80.881571769714355), 
#  (6.9233804941177368, 21.640089154243469, 99.177539348602295, 41.364166140556335)]
like image 121
Austin Avatar answered Jan 29 '23 16:01

Austin