How to Change Values in a Tuple

How to change values in a tuple?

It's possible via:

t = ('275', '54000', '0.0', '5000.0', '0.0')
lst = list(t)
lst[0] = '300'
t = tuple(lst)

But if you're going to need to change things, you probably are better off keeping it as a list

Changing values in a tuple

Convert it to a list and update the values. And the you can change it back to tuple.

Ex:

tup = [('a', '10', 0xA), ('b', '9', 0x9)]
res = []
for i in tup:
val = list(i)
val[-1] = 0x99
res.append(tuple(val))

print(res)

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

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

What is an elegant way to change an element of a tuple?

I would use collections.namedtuple instead:

>>> from collections import namedtuple

>>> class Foo(namedtuple("Foo", ["a", "b", "c"])):
pass

>>> f = Foo(1, 2, 3) # or Foo(a=1, b=2, c=3)
>>> f._replace(a = 5)
Foo(a=5, b=2, c=3)

namedtuples also support indexing so you can use them in place of plain tuples.

If you must use a plain tuple, just use a helper function:

>>> def updated(tpl, i, val):
return tpl[:i] + (val,) + tpl[i + 1:]

>>> tpl = (1, 2, 3)
>>> updated(tpl, 1, 5)
(1, 5, 3)

Changing values of tuple elements

It is simple. In Python, the names, such as a and b and t are not objects, they just point to objects. When you enter

>>> a = 25
>>> b = 50

Python sets the name a to point to an int object with value 25 and b to point to int object with value 50.

when you create a tuple with

>>> t = a, b

(no parenthesis required here!) you're telling Python that "please make a new tuple of 2 elements, the first position of which should point to the object that a now points to and the second position should point to the object that b now points to. Actually it would work similarly with a list, or set as well:

>>> l = [a, b]
>>> s = {a, b}

Now the next statement:

>>> a = 50

Means "now, set a to point to an int object with value of 50". The first element of the tuple still continues to point to 25. Actually all assignments to variables behave this way in Python, be the value in a mutable or not:

>>> a = [1, 2]
>>> b = [3, 4]
>>> t = a, b
>>> a = [5, 6]
>>> t
([1, 2], [3, 4])

Even though a points to a mutable value, a list, then a, b means *make a new tuple with first element being the object that a points to at this very moment, and second element being the object that b points to at this very moment; and then a = [5, 6] means *create a new list ... and now make a point to it`. The variables (names) in Python indeed are not "boxes", but they're sort of signs that point to the values.

Python - Update a value in a list of tuples

Your data structure (a list of tuple) is best referred as an associative list. As other pointed out, it is probably better to use a dictionary as you'll get better amortized cost on operation (insertion, deletion, and lookup are O(1) for a dictionary, but deletion and lookup are O(n) for associative list).

Concerning updating your associative list by converting it to a dictionary, and then back to an associative list, this method has three drawbacks. It is quite expensive, it may change the order of the items, and it will remove duplicate.

If you want to keep using associative lists, it is probably better to just use a list comprehension to update the data structure. The cost will be O(n) in time and memory, but that's already what you have when using an intermediate dictionary.

Here's a simple way to do it (require Python 2.5 because it use the ternary operator):

def update_in_alist(alist, key, value):
return [(k,v) if (k != key) else (key, value) for (k, v) in alist]

def update_in_alist_inplace(alist, key, value):
alist[:] = update_in_alist(alist, key, value)

>>> update_in_alist([('a', 'hello'), ('b', 'world')], 'b', 'friend')
[('a', 'hello'), ('b', 'friend')]

Changing first value of a tuple inside a tuple list

Since tuple is an immutable type, you cannot change the elements/content of tuples.

For your case, what you can do is generate a list with new tuples.

Try this:

my_list = [('www.url.com/index.html', 'url'), 
('www.website.org/id/1234/photos', '1234 Photos'),
('www.test.com', 'test')]

f = lambda x: x.split('/')[0]
my_list = [(f(url),name) for url, name in my_list]
print(my_list)

Output:

[('www.url.com', 'url'), ('www.website.org', '1234 Photos'), ('www.test.com', 'test')]

Updating a value in a tuple-value in nested dictionary in python

As you noted yourself, tuples are immutable. You cannot change their contents.

You can of course always just create a new tuple with the updated value and replace the old tuple with this one.

Something like

Diction = {'stars': {(4, 3): (2, 3, 100, 0), (3, 4): (3, 2)}}
temp = list(Diction['stars'][(4,3)])
temp[-1] = 8765
Diction['stars'][(4,3)] = tuple(temp) # convert back to a tuple

Python: Change tuple in a list of tuples

I think assigning the updated tuple to the corresponding index in the list will solve the issue since tuples are immutable. To keep the corresponding index enumerate can be used while iterating through the list. You can try following:

recordlist = [('sku1','item1','bro1'),('sku2','item2','bro2')]

for index, item in enumerate(recordlist):
itemlist = list(item)
if itemlist[0] == 'sku1':
itemlist[1] = itemlist[1]+','+'item'
item = tuple(itemlist)

recordlist[index] = item

print(recordlist)

Output:

[('sku1', 'item1,item', 'bro1'), ('sku2', 'item2', 'bro2')]

Is there a way to change tuple values inside of a C# array?

Tuple by design is immutable. Just create new one when modifying.

IEnumerable<Tuple<int, int, int>> Get()
{
for (int i = 0; i < 10; i++)
{
yield return Tuple.Create(i, 0, 0);
}
}

IEnumerable<Tuple<int, int, int>> Modify(IEnumerable<Tuple<int, int, int>> tuples)
{
foreach (var tuple in tuples)
{
if (tuple.Item1 < 5)
{
yield return Tuple.Create(tuple.Item1, tuple.Item2 + 1, tuple.Item3);
}
else
{
yield return Tuple.Create(tuple.Item1, tuple.Item2, tuple.Item3 + 1);
}
}
}

Your code looks like javascript more than C#. int[,,] is 3D array not array of 3 items.

Tuple<int, int, int>[] is an array of Tuple of 3 items. If you are not a beginner and use LINQ, IEnumerable<Tuple<int, int, int>> is a better version.



Related Topics



Leave a reply



Submit