New user questions ... be gentle

Alex Martelli alex at magenta.com
Mon Aug 21 09:42:06 EDT 2000


"bushi" <bushi at spiritone.com> wrote in message
news:399FC343.FECFA832 at spiritone.com...
    [snip]
> I use pointers and linked lists a lot in the other languages.  I have
> seen some references that hint to a way to do this but it isn't very
> clear.  Any pointers on this would be very helpful. *grins*

In a sense, Python has "nothing-but" pointers, aka references.  Any
variable, any 'slot' in a Python list, any 'slot' in a Python dict,
any attribute of a Python object, ..., is-a/holds-a reference to
something, which acts much as a pointer does in Pascal.

Python's high-level structures, lists and dictionaries, reduce your
need for any explicit 'thinking about' these pointers/references as
such, to much rarer cases than it would be in Pascal or other lower
level languages.  However, it still happens, and, when it does, you
just have to _remember_ what these references ARE.  After which, you
can proceed much like in Pascal (at worst; there are often useful
shortcuts, but, you don't _have_ to use them).

For example, in Pascal you would construct a linked-list out of
records, each representing a 'node' of the linked-list, and also
holding a pointer to the 'next' node (and maybe to the 'previous'
one too, if you want a _doubly_ linked list) as well as some
'payload' which is the actual data for this node.

OK, you can do that in Python, too, if you wish:

class node:
    def __init__(self, payload, next=None):
        self.payload = payload
        self.next = next

Given a value head, that can be None or else a node (the first one
in a list), you prepend a new node carrying payload 'foo' to the
(possibly-now-empty) list by:

    head = node('foo',head)

To remove the head-node from a non-empty linked list built this
way,
    if head:
        removed,head = head,head.next
        print 'Removed:',removed.payload
    else:
        print 'List is empty'


Etc, etc.  You don't normally need to do this, but, if you do need
(or want, e.g. for didactical purposes), it's as easy as this.


Alex






More information about the Python-list mailing list