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?
Python has a great built-in list type named "list". List literals are written within square brackets [ ]. Lists work similarly to strings -- use the len() function and square brackets [ ] to access data, with the first element at index 0.
A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements. Each element or value that is inside of a list is called an item. Just as strings are defined as characters between quotes, lists are defined by having values between square brackets [ ] .
One of the reasons it's so handy is Python slice notation. In short, slicing is a flexible tool to build new lists out of an existing list. Python supports slice notation for any sequential data type like lists, strings, tuples, bytes, bytearrays, and ranges. Also, any new data structure can add its support as well.
With this operator, one can specify where to start the slicing, where to end, and specify the step. List slicing returns a new list from the existing list. If Lst is a list, then the above expression returns the portion of the list from index Initial to index End, at a step size IndexJump.
[:]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With