1

I tried to understand [:] in the beginning, but I can't find any document mention it. Where is the best place to learn advanced grammar for Python? Google search won't find [:]. But I figured it out at the end. I just wonder where is best place to learn Python 'tricks'.

For example:

def test(x, y):
    x[:] = y  
    #x = y

>>> a = [0.5,0.6]
>>> b = [0.3]
>>> test(a, b)
>>>
>>> print a
[0.3]  # [0.5,0.6] 
Bharel
  • 23,672
  • 5
  • 40
  • 80
Jerry
  • 23
  • 1
  • 3

3 Answers3

8

x[:] means the entire sequence. It's basically x[from:to].

Omitting from means, from the beginning until the to.

>>> numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numbers[:5]
[0, 1, 2, 3, 4]

Omitting to means, from the from until the end.

>>> numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numbers[5:]
[5, 6, 7, 8, 9]

Omitting both means the entire list.

>>> numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numbers[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Setting numbers[:] means setting the entire list:

>>> numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numbers[:] = [1, 2, 3, 4]
>>> numbers
[1, 2, 3, 4]

Keep in mind setting numbers[:] changes that list and does not create a new one. The object will still have the same id().

Bharel
  • 23,672
  • 5
  • 40
  • 80
4

The term you need to search for is slice. x[start:end:step] is the full form, any one can be omitted to use a default value: start defaults to 0, end defaults to the length of the list, and step defaults to 1. So x[:] means exactly the same as x[0:len(x):1]. You can find more information at the Expression section of the language reference, and section four of the python tutorial might also be helpful.

RoadieRich
  • 6,330
  • 3
  • 35
  • 52
  • Not to mention [stack overflow](http://stackoverflow.com/questions/509211/explain-pythons-slice-notation) itself. – Robᵩ Mar 30 '16 at 19:33
0

The notation x[:] is equivalent to x[0:n] where n is len(x). It specifies the range of elements of x from 0 through n-1 inclusive.

When read, a new list, string, or whatever is created, containing the specified range of elements.

When assigned to, the specified range of elements is destructively replaced in the original. Note that this is allowed for lists, but not for strings.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41