Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 417
Petr S Avatar asked Apr 30 '15 09:04

Petr S


People also ask

What is the notation for list in Python?

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.

What * list means in Python?

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 [ ] .

What is Python slice notation?

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.

How does slicing a list work Python?

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.


1 Answers

[:] 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.

like image 193
Frerich Raabe Avatar answered Oct 14 '22 01:10

Frerich Raabe