Search code examples
pythondocutils

Python dictionary "copy value"


I was looking at the docutil source code (which is in python), when I saw this (redacted) :

def __init__(self, **attributes):
    for att, value in attributes.items():
        att = att.lower()
        if att in self.list_attributes:
            # mutable list; make a copy for this node
            self.attributes[att] = value[:]
        else:
            self.attributes[att] = value

The line I'm talking about is this one:

            self.attributes[att] = value[:]

What does the "[:]" do exactly ? The comment above it hint a copy of some kind but my google searchs were not that successful and I can't figure if it's a language feature or a trick/shortcut of some kind.


Solution

  • It makes a copy of the list (it's not a dictionary)

    The notation is called "slicing". You can also specify where to start and end copying, if you don't specify anything - as in your code extract - it will copy from the first to the last element.

    For instance, mylist[1:] will copy the entire list omitting the first element.

    Have a look here for a comprehensive explanation.