120

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?

codeforester
  • 39,467
  • 16
  • 112
  • 140
andriy
  • 4,074
  • 9
  • 44
  • 71
  • 1
    Related, clearing a list is only possible by doing del pop[:] or pop[:] = [], not pop.clear() .. (as you do with dicts). – Macke May 30 '11 at 09:14
  • Good SO discussion of Python slice: http://stackoverflow.com/questions/509211/explain-pythons-slice-notation – Scott C Wilson Jul 02 '16 at 20:44
  • @Macke: Note: As of Python 3.3, `list`s do provide `clear` and `copy` methods, equivalent to doing `del mylist[:]` or `mylist[:]` respectively. They're not required on mutable sequences in general, so if you might receive an arbitrary mutable sequence, you'd want to stick to slice based operations, but the named methods are at least available on `list`. – ShadowRanger Nov 02 '20 at 19:28
  • @ShadowRanger Yeah, 9 years later. :-) – Macke Nov 05 '20 at 14:47

6 Answers6

131

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.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • 14
    Just in case: the slice returns a shallow copy. – André Caron May 29 '11 at 15:45
  • Using `l.copy()` for a list may be more readable than `l[:]`, unless 4 characters longer. – saeedgnu May 29 '11 at 16:37
  • 4
    @ilius: Maybe `l.copy()` is more readable, but it won't work. – Sven Marnach May 29 '11 at 16:47
  • 13
    `list(l)` always works, is more readable, and is guaranteed to return a copy even with something like `numpy.array` – Rosh Oxymoron May 29 '11 at 18:05
  • @SvenMarnach: stay tuned for 3.3, where `list.copy` has been added – Eli Bendersky Nov 12 '11 at 03:50
  • 1
    @Eli: Yes, alongside `list.clear()`. It will take some time, though, until this will lead to a significant reduction of this kind of questions on SO. :) – Sven Marnach Nov 12 '11 at 15:53
  • Since I couldn't find this anywhere on line, the way to express that colon programmatically is `slice(None)`. So the above is equivalent to `x = slice(None)` then `pop = population(x)`. Very useful for multidimensional arrays. Instead of `A[:,0,:]` you can determined from which dimension to get a slice programmatically. `x = deque(chain((0,), repeat(slice(None), dim-1))` then `A[x.rotate(position)]` – Michael Graczyk Apr 06 '14 at 01:05
  • 1
    @MichaelGraczyk: I assume you are talking about NumPy arrays here. Rather than using `A[deque(chain((k,), repeat(slice(None), len(A.shape) - 1)).rotate(axis)]`, I'd almost always prefer `numpy.rollaxis(A, axis, 0)[k]`. In general, I've rarely come across a use case where you would need to directly create `slice()` objects. If you need them anyway, NumPy provides the [`s_`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.s_.html#numpy.s_) helper as an alternative way to create them. – Sven Marnach Apr 07 '14 at 10:20
  • @SvenMarnach, thanks, I did not know about rollaxis. – Michael Graczyk Apr 07 '14 at 21:11
  • 1
    @EthanFurman: the slice does not automatically convert to list. For example `(1,2,3)[:]` will yield the tuple `(1, 2, 3)` – F1Rumors Aug 25 '16 at 18:37
35

It might also help to know that a list slice in general makes a copy of part of the list. E.g. population[2:4] will return a list containing population[2] and population[3] (slicing is right-exclusive). Leaving away the left and right index, as in population[:] they default to 0 and length(population) respectively, thereby selecting the entire list. Hence this is a common idiom to make a copy of a list.

ThomasH
  • 22,276
  • 13
  • 61
  • 62
17

well... this really depends on the context. Ultimately, it passes a slice object (slice(None,None,None)) to one of the following methods: __getitem__, __setitem__ or __delitem__. (Actually, if the object has a __getslice__, that will be used instead of __getitem__, but that is now deprecated and shouldn't be used).

Objects can do what they want with the slice.

In the context of:

x = obj[:]

This will call obj.__getitem__ with the slice object passed in. In fact, this is completely equivalent to:

x = obj[slice(None,None,None)]

(although the former is probably more efficient because it doesn't have to look up the slice constructor -- It's all done in bytecode).

For most objects, this is a way to create a shallow copy of a portion of the sequence.

Next:

x[:] = obj

Is a way to set the items (it calls __setitem__) based on obj.

and, I think you can probably guess what:

del x[:]

calls ;-).

You can also pass different slices:

x[1:4]

constructs slice(1,4,None)

x[::-1]

constructs slice(None,None,-1) and so forth. Further reading: Explain Python's slice notation

Community
  • 1
  • 1
mgilson
  • 300,191
  • 65
  • 633
  • 696
12

It is a slice from the beginning of the sequence to the end, usually producing a shallow copy.

(Well, it's more than that, but you don't need to care yet.)

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
7

[:]
used for limiter or slicing in array , hash
eg:
[1:5] for displaying values between 1 inclusive and 5 exclusive i.e 1-4
[start:end]

basically used in array for slicing , understand bracket accept variable that mean value or key to display, and " : " is used to limit or slice the entire array into packets .

Sean Colombo
  • 1,459
  • 17
  • 24
  • 1
    No reason to bump such an old question which already has 5 similar answers and even an accepted one... Besides, `a[1:5]` returns elements 1-4, not 2-4. – Skamah One Jul 03 '13 at 12:25
  • @SkamahOne Oh I don't know. Maybe not in this case but there are times where it can be of value to raise dead questions. Different insight, different wording etc. In this case you corrected the answer and they hopefully learnt something too. – Pryftan Apr 19 '20 at 15:17
7

It creates a copy of the list, versus just assigning a new name for the already existing list.

Jim Brissom
  • 31,821
  • 4
  • 39
  • 33