S Andrew
S Andrew

Reputation: 7298

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?

Upvotes: 4

Views: 4893

Answers (3)

jpp
jpp

Reputation: 164843

Tuples are immutable. A list of tuples is not the best structure for what you're looking to do. If you can use a 3rd party library, I recommend NumPy:

import numpy as np

A = np.array(my_list)
A *= 100

print(A)

array([[ 12.49700785,  37.18652725,  96.81450129,  55.42989373],
       [ 18.75786483,  61.71307564,  84.82183218,  80.88157177],
       [  6.92338049,  21.64008915,  99.17753935,  41.36416614]])

The alternative is a list comprehension, which doesn't work in place.

Upvotes: 1

Austin
Austin

Reputation: 26057

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

Upvotes: 6

Kevin K.
Kevin K.

Reputation: 1407

You cannot reassign values to tuples because they are immutable. Try creating a new 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)]
my_list = [tuple(map(lambda x: x*100, item)) for item in my_list]

Upvotes: 1

Related Questions