0

The full source code is @ PEP 333. These two lines:

status, response_headers = headers_sent[:] = headers_set

.. and ..

headers_set[:] = [status, response_headers]

What am I looking at here? How does [:] differ from giving nothing at all (just headers_set)? If someone could provide an explanation, I'd be really glad.

maligree
  • 5,939
  • 10
  • 34
  • 51

1 Answers1

4

[:] means that you are overwriting the entire list's contents.

>>> a = [1,2,3]
>>> a[:] = [3,4]
>>> a
[3, 4]
>>> a[]
  File "<stdin>", line 1
    a[]
      ^
SyntaxError: invalid syntax

And you can use the same syntax to overwrite some index range of the list:

>>> a[2:] = [3,4]
>>> a
[3, 4, 3, 4]
sinelaw
  • 16,205
  • 3
  • 49
  • 80
  • And the difference between doing `a = [1,2,3]` and `a[:] = [1, 2, 3]`? Anyway, Ignacio pretty much answered it all. – maligree Jul 12 '11 at 09:47
  • 1
    The difference is that `a = [1,2,3]` creates an entirely new list object, and stores a reference to it in `a`, discarding the reference to the old list `a` pointed to. `a[:]=[1,2,3]` on the other hand takes the old list `a` referenced, and replaces the contents with `[1,2,3]`. Er, hard to do in comments but - say `a = [1,2,3]; b = a; a = [4,5,6]`.. `a` will now point to diff list, but `b` will still reference the old list. Whereas for `a = [1,2,3]; b=a; a[:] = [4,5,6]`... both `a` and `b` will reference orig list, but it will now contain `4,5,6`. – Eli Collins Jul 13 '11 at 03:44