The following code is not returning None but some mysterious “main_.link_list object”:
class link_list(object):
"""a link list class"""
def __init__(self, list):
super(link_list, self).__init__()
pdb.set_trace()
if list==[]:
return None
else:
self.value = list[0]
self.next = link_list(list[1:len(list)])
Test code prints ‘False’:
l=link_list([1,2,3])
print l.next.next.next==None
Why?
.__init__()is not really a constructor.__init__ as a constructor?
The object will be created whether or not you return
Nonefrom.__init__(). As @Ignacio Vazquez-Abrams noted in the comments, Python expectsNoneas the return value from.__init__(); you can’t return anything else anyway. If you need to signal some sort of catastrophic error, you should raise an exception.In your example, you should probably have a class that represents a complete linked list, with a “head” reference and a “tail” reference, and another class that represents a data entry in the linked list. Then the linked list class itself can be tested for a null list by checking to see if
head is None.EDIT: Upon a little bit of further thought, your single-class implementation will work; it’s just that we need to set
.nexttoNoneinside.__init__(). Here is my edit of your code:Notes:
I fixed the indentation.
I used
lstinstead oflistfor the variable name, so as not to shadow the built-in typelist.I added some print statements to help you watch what is going on.
EDIT: And, for completeness, here is an implementation using two classes: a class that represents a list and might be zero-length, and a class that represents one entry in the list. A
forloop builds the chain of entries, and can build a list from any sequence (including an iterator); slicing is not used so the sequence does not have to be a list.EDIT: Here’s one more version. This uses iteration to build the linked list, not tail recursion, but does it with a single class. The trick is that the
.__init__()function needs to know whether it is building a whole linked list, or just making one instance to be used to build a linked list; hence the check forseq is None. If the user passes in a sequence,.__init__()builds a whole linked list, but otherwise it just makes one instance to be used as a link in the list.First we get a new iterator from the sequence. Then we attempt to pull a value from the sequence with
next(). If this fails we have a zero-length linked list and return it; if this succeeds, we use that value for the head of the linked list and then loop over the rest of the values from the sequence.Playing directly with iterators may seem tricky, but I think it is the cleanest way to handle cases like this, where we want to pull the first item from the sequence and then loop over the remaining ones, and we don’t want to use slicing (and thus only work with an actual list).