Addressing the last element of a list
Antoon Pardon
apardon at forel.vub.ac.be
Thu Nov 10 10:06:23 EST 2005
Op 2005-11-10, Steven D'Aprano schreef <steve at REMOVETHIScyber.com.au>:
> On Thu, 10 Nov 2005 06:47:41 +0000, Donn Cave wrote:
>
>> Quoth Steven D'Aprano <steve at REMOVETHIScyber.com.au>:
>> ...
>> | So when working with ints, strs or other immutable objects, you aren't
>> | modifying the objects in place, you are rebinding the name to another
>> | object:
>> |
>> | py> spam = "a tasty meat-like food"
>> | py> alias = spam # both names point to the same str object
>> | py> spam = "spam spam spam spam" # rebinds name to new str object
>> | py> print spam, alias
>> | 'spam spam spam spam' 'a tasty meat-like food'
>>
>> The semantics of assignment are like that, period. If the right hand
>> side is an int, a string, a class instance, a list, whatever, doesn't
>> matter at all. The question of mutability at this point can be a red
>> herring for someone who doesn't already understand these matters.
>
> Yes, but in the context we were discussing, the original poster was
> specifically asking to do something that is only possible with mutable
> objects.
>
> He wanted to do something like this:
>
> data = [0, None, 2, ["hello"]]
> ref = data[-1]
> ref.append("world")
>
> and end up with [0, None, 2, ["hello", "world"]]. That will work, because
> the last item in data is mutable. But this will NOT work:
>
> data = [0, None, 2, 0]
> ref = data[-1]
> ref = 1
> assert data[-1] == 1
>
> because ints are immutable. So the distinction between modifying a
> mutable object in place and assigning is important.
I wonder couldn't this be done with properties?
Write somekind of property so that if you manipulate a.x it would
manipulate data[-1]
--
Antoon Pardon
More information about the Python-list
mailing list