Implementing pointers in Python

This is the place for queries that don't fit in any of the other categories.

Implementing pointers in Python

Postby Yuval » Wed Aug 14, 2013 11:25 am

Hey there,

Would appreciate very much help on this data structure issue:

I want to create an object of type "event" which will include for example the fields "bike", "station","time". My goal is to keep each object of this class only once in the computer's memory but to be part of two different lists - one of a certain value of "bike" and one of a certain value of "station". Like using pointers in C.

an illustration is provided as attachment.

A huge thanks in advance,

Data structure illustration.png
Data structure illustration.png (10.81 KiB) Viewed 785 times
Posts: 1
Joined: Wed Aug 14, 2013 11:03 am

Re: Implementing pointers in Python

Postby stranac » Wed Aug 14, 2013 12:10 pm

If you store the same object in two different lists, it won't be stored twice in memory.
Both lists will contain a reference to the same object.

I have no idea what the picture is supposed to mean...
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
Posts: 1790
Joined: Thu Feb 07, 2013 3:42 pm

Re: Implementing pointers in Python

Postby Mekire » Wed Aug 14, 2013 12:12 pm

If you put an instance of a class in two different lists, there is still only one object. If you change one you change the other. Everything in python is a reference; the distinction is just mutable and immutable.

Code: Select all
class MyClass(object):
    def __init__(self,x):
        self.x = x

    def __repr__(self):
        return "MyClass({})".format(repr(self.x))

some_instance = MyClass(0)
a = [some_instance,5,"spam"]
b = ["something","nothing",some_instance]


a[0].x = "Wow, I changed in both lists."

Code: Select all
[MyClass(0), 5, 'spam']
['something', 'nothing', MyClass(0)]
[MyClass('Wow, I changed in both lists.'), 5, 'spam']
['something', 'nothing', MyClass('Wow, I changed in both lists.')]

As you can see changing it in one changed the corresponding one in the other.

Edit: Simplified.
New Users, Read This
  • Use code tags when posting code.
  • Include any errors with your post (in code tags).
  • Describe your problem; not your chosen solution.
  • Make examples the minimum length to demonstrate your issue.
User avatar
Posts: 1711
Joined: Thu Feb 07, 2013 11:33 pm
Location: Tucson, Arizona

Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 7 guests