Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How do I differentiate between two list elements that point to the same object?

Tags:

python

I have a Ring structure implemented as follows (based on a cookbook recipe I found):

class Ring(list):

    def turn(self):
        last = self.pop(0)
        self.append(last)

    def setTop(self, objectReference):
        if objectReference not in self:
            raise ValueError, "object is not in ring"

        while self[0] is not objectReference:
            self.turn()

Say I do the following:

x = Ring([1,2,3,4,4])
x.setTop(4)

My code will always set the first 4 (currently x[3]) to x[0]. It seems (via object identity and hash id testing between x[3] and x[4]) that Python is reusing the 4 object.

How do I tell Python that I really want the second 4 (currently x[4]) to be at the top?

Apologies for the basic question ... one of the downfalls of being a self-taught beginner.

Thanks,

Mike

===EDIT===

For what it's worth, I dropped the setTop method from the class. I had added it to the standard recipe thinking "hey, this would be neat and might be useful." As the answers (esp. "what's the difference", which is spot on) and my own experience using the structure show, it's a crappy method that doesn't support any of my use cases.

In other words, adding something because I could instead of fulfilling a need = fail.

like image 475
MikeRand Avatar asked Feb 27 '23 03:02

MikeRand


2 Answers

From Learning Python, 4th edition -- Chapter 6:

At least conceptually, each time you generate a new value in your script by running an expression, Python creates a new object (i.e., a chunk of memory) to represent that value. Internally, as an optimization, Python caches and reuses certain kinds of un- changeable objects, such as small integers and strings (each 0 is not really a new piece of memory—more on this caching behavior later). But, from a logical perspective, it works as though each expression’s result value is a distinct object and each object is a distinct piece of memory.

The question is..

if x[3] is x[4]:
    print "What's the difference?"
like image 103
sleepynate Avatar answered Apr 20 '23 01:04

sleepynate


If you know you want the second, then do

x = Ring([1,2,3,4,4])
x.setTop(4)
x.turn()
x.setTop(4)

You can enhance setTop() to take an additional parameter and do it inside.

like image 24
Wai Yip Tung Avatar answered Apr 19 '23 23:04

Wai Yip Tung