[Tutor] List problem

Peter Otten __peter__ at web.de
Mon Jul 25 10:07:13 CEST 2011


David Merrick wrote:

>     def append(self,item):
>          '''Adds an item to the end of the List'''
> 
>          current = self.head
>          previous = None
>          while current.getNext() != None:
>              previous = current
>              current = current.getNext()
>          if current.getNext() == None:
>              previous  = previous.setNext(current)
>              current = current.setNext(item)

> myList.append(24)

Your append() method expects item to be a Node instance, so you have to wrap 
your data (24 in the example) into a Node

myList.append(Node(24))

or modify append() accordingly. Note that there is at least one other 
problem with your append() implementation: you cannot append to an empty 
UnorderedList because you don't handle the case where self.head is None.

Stylistically your code looks like a literal translation from Java; in 
Python it is good practice to avoid getter/setter methods and use attributes 
(or properties) instead. Also, we have a cool way to implement iteration: 
generators.

#untested
class UnorderedList(object):
    def __iter__(self):
        current = self.head
        while current is not None:
            yield current.data

You can then write

print 24 in myList

instead of

print myList.search(24)

In idiomatic Python you'd call the length() method __len__() and invoke it 
as

print len(myList)



More information about the Tutor mailing list