linkyndy
linkyndy

Reputation: 17900

Slice vs normal assignments

I stumbled upon UserList's implementation and don't seem to understand why in the __init__() method both slice assignments and normal assignments are used to set the given initial list. Here's the code:

class UserList(collections.MutableSequence):
    def __init__(self, initlist=None):
        self.data = []
        if initlist is not None:
            # XXX should this accept an arbitrary sequence?
            if type(initlist) == type(self.data):
                self.data[:] = initlist
            elif isinstance(initlist, UserList):
                self.data[:] = initlist.data[:]
            else:
                self.data = list(initlist)

Why are both self.data[:] and self.data used when assigning the initial list?

Upvotes: 0

Views: 89

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121524

You are correct, the code is redundant. But it wasn't in 2000 when Jeremy Hylton made the change.

Now slice assigment takes any sequence type, but that feature was only added in Python 2.3 (specifically, it was Alex Martelli who added support for any type to be used).

So at the time the code was written, it made perfect sense to make use of slice assignment and not create a new list object, but only if you had an object that actually could be used on the right-hand side for such an assignment. Slice assignment was a fast and efficient way to copy the list contents over.

Upvotes: 2

Related Questions