wesanyer
wesanyer

Reputation: 1002

Python Custom List Class - Slicing Self

I have the following custom class that is intended to truncate itself when it is of length greater than 5. When stepping through the code, the slice operation DOES occur, but when control returns to the caller the stored topFiveList instance remains of length > 5. What am I doing incorrectly here?

class topFiveList(list):
    def add(self, key, value):
        index = -1
        for i, pair in enumerate(self):
            if pair[1] < value:
                index = i
                break
        if index == -1:
            self.append([key, value])
        else:
            self.insert(index, [key, value])
        if len(self) > 5:
            self = self[:5]

testvals = [['six', 6], ['one',1], ['five',5], ['nine', 9], ['three',3], ['four', 4], ['seven', 7]]
topFive = topFiveList()
for text, value in testvals:
    topFive.add(text, value)

Upvotes: 0

Views: 188

Answers (1)

vaultah
vaultah

Reputation: 46533

self = self[:5] does not modify the self instance, it simply binds the local variable self to the created slice self[:5].

However, you could use slice assignment.

self[:] = self[:5]

and

self[5:] = []

both achieve the same.

The first option replaces the contents of self with self[:5]. OTOH the second option will simply remove everything starting from position 5.

Upvotes: 3

Related Questions