Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does [:] mean?

I'm analyzing some Python code and I don't know what

pop = population[:] 

means. Is it something like array lists in Java or like a bi-dimensional array?

like image 232
andriy Avatar asked May 29 '11 10:05

andriy


People also ask

What does [: I mean in Python?

If based on numpy , ans[i,:] means to pick the ith 'row' of ans with all of its 'columns'. Note,when dealing with numpy arrays, we should (almost) always use [i, j] instead of [i][j] . This might be counter-intuitive if you used Python or Java to manipulate matrix before. Follow this answer to receive notifications.

What does [: 1 :] mean in Python?

In Python, [::-1] means reversing a string, list, or any iterable with an ordering. For example: hello = "Hello world" nums = [1, 2, 3, 4] print(hello[::-1])

What does list [:] do in Python?

Definition and Usage. The list() function creates a list object. A list object is a collection which is ordered and changeable. Read more about list in the chapter: Python Lists.

What does arr [:] mean in Python?

arr[:]=arr2 performs an inplace replacement; changing the values of arr to the values of arr2 . The values of arr2 will be broadcasted and copied as needed. arr=arr2 sets the object that the arr variable is pointing to. Now arr and arr2 point to the same thing (whether array, list or anything else).


1 Answers

It is an example of slice notation, and what it does depends on the type of population. If population is a list, this line will create a shallow copy of the list. For an object of type tuple or a str, it will do nothing (the line will do the same without [:]), and for a (say) NumPy array, it will create a new view to the same data.

like image 191
Sven Marnach Avatar answered Sep 20 '22 18:09

Sven Marnach