More pythonic way to change an element of a tuple?

Manuel M. Garcia mgarcia at cole-switches.com
Wed Nov 27 14:11:18 EST 2002


On Wed, 27 Nov 2002 09:58:44 -0800, Richard Muller
<rpm at wag.caltech.edu> wrote:
(edit)
>I frequently have to change a single element of a tuple, and I wind up 
>doing something like this:
>tmp = list(data_in_tuple)
>tmp[item] += 1
>data_in_tuple = tuple(tmp)

maybe keep it always in a list, and just when you need to have a
tuple, use the tuple() function to make a change:

list0 = [1,2,3]
list0[1] += 1
dict0 = {}
dict0[tuple(list0)] = 3
try:
    dict0[list0] = 4
except TypeError:
    print ('whoops, lists are unhashable, ' +
           'cannot be used as dictionary key')
print 'dict0:%r' % (dict0)

Please be careful, everytime you use tuple() a brand new tuple is
created, independent from all other created before!

a = (1,2,3)
b = a
temp = list(a)
temp[1] += 1
a = tuple(temp)
print 'different! a:%r, b:%r' % (a, b)

c = [1,2,3]
d = c
c[1] += 1
print 'same! c:%r, d:%r' % (c, d)

Manuel



More information about the Python-list mailing list