How may I change values in tuples of list of lists?

Ben Finney ben+python at benfinney.id.au
Wed Feb 24 00:34:35 EST 2016


subhabangalore at gmail.com writes:

> Now if I want to change the values of tags like 'AT', 'NP-TL',
> 'NN-TL', etc. to some arbitrary ones like XX,YY,ZZ and yet preserve
> total structure of tuples in list of lists, please suggest how may I
> do it. 

Changing items in lists is done by assigning to an index in that list,
using index syntax::

    big_list[17] = new_value

This works because a list is a homogeneous mutable sequence: no position
in the sequence has any special meaning, and you can change any of the
items in the sequence to refer to a different value.

Choosing the list type to represent a structure is a choice to express
“this sequence doesn't mean anything except the particular ordering of
these items, and changing any of the values doesn't change the meaning
of this sequence”.


I think your question boils down to “how do I change one item in a
tuple?”. If that's the essence of the question, the other stuff about
where the tuple is found are irrelevant to solving this.

The answer to that question is: you don't. Instead, you create a new
tuple.


A tuple is immutable; the programmer, by choosing the tuple type, has
chosen to express “this sequence is a single complex value, where the
total set of items in this order has its own meaning, and if any of its
items were different this would have a different meaning”.

So, to create a new tuple based on an existing tuple, you need to
specify each item in the new tuple. If you want some of the items in the
new tuple to be from the existing tuple, you need to access those.

    foo = ('Fulton', 'NP-TL')
    bar = tuple(foo[0], 'XX')

Is this awkward? Yes, so you should be thinking hard about whether
you're fighting against the intent of the existing data structure.

The programmer either made a bad design choice; or the choice of tuple
type was for a good purpose. You should lean toward the latter until you
know more about the program.

-- 
 \      “It seems intuitively obvious to me, which means that it might |
  `\                                           be wrong.” —Chris Torek |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list