2

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.

Sebastien F.
  • 1,613
  • 2
  • 23
  • 40

1 Answers1

8

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.

Community
  • 1
  • 1
phant0m
  • 16,595
  • 5
  • 50
  • 82
  • Thank you, it answers my question perfectly. I'll mark it as an answer as soon as the site allows me too (in 8 minutes more or less) – Sebastien F. Jul 29 '12 at 17:22
  • Note that it is not a deep copy; it simply copies the references to each object and stores them in a new list. While this should not be your copy method of choice for everything, it is useful if you want to iterate over and modify a list at the same time without screwing up your iteration. – algorowara Jul 29 '12 at 22:27