pythonlistslicenotationshallow-copy

What does this notation do for lists in Python: "someList[:]"?


I sometimes get across this way of printing or returning a list - someList[:]. I don't see why people use it, as it returns the full list.

Why not simply write someList, whithout the [:] part?


Solution

  • [:] creates a slice, usually used to get just a part of a list. Without any minimum/maximum index given, it creates a copy of the entire list. Here's a Python session demonstrating it:

    >>> a = [1,2,3]
    >>> b1 = a
    >>> b2 = a[:]
    >>> b1.append(50)
    >>> b2.append(51)
    >>> a
    [1, 2, 3, 50]
    >>> b1
    [1, 2, 3, 50]
    >>> b2
    [1, 2, 3, 51]
    

    Note how appending to b1 also appended the value to a. Appending to b2 however did not modify a, i.e. b2 is a copy.