Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does list[x::y] do? [duplicate]

Tags:

python

syntax

Possible Duplicate:
Good Primer for Python Slice Notation

I've been reading over some sample code lately and I've read quite a few websites but I just can't seem to get the query right to give me an answer I'm looking for. If anyone could help me out I'd appreciate it.

like image 865
pri0ritize Avatar asked Jan 27 '12 01:01

pri0ritize


People also ask

What does :: mean in list?

So: [start::] will return the list starting from 'start' until the last element [:end:] will return all from the first element until the one preceding 'end' [0:-3] will return elements starting from the first one until (but not including) the third to last [::2] will return every second element of the list [::-3] will ...

What does :: 2 do in Python?

string[2::2] reads “start index of two, default stop index, step size is two—take every second element starting from index 2“.


2 Answers

It slices

x[startAt:endBefore:skip] 

if you use skip = 2, every other element the list beginning at startAt and ending at endBefore will be selected. [Remember: indices live BETWEEN list elements]

To see this, enter

x = range(100) 

at the Python prompt. Then try these things

x[::2] x[::3] x[10:40:6] 

and see what happens.

like image 109
ncmathsadist Avatar answered Sep 28 '22 06:09

ncmathsadist


L[x::y] means a slice of L where the x is the index to start from and y is the step size. Here are some examples you can try in the interpreter

>>> L=range(20) >>> L [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] 

If you want every 3rd element

>>> L[::3] [0, 3, 6, 9, 12, 15, 18] 

Now every third element starting from L[1]

>>> L[1::3] [1, 4, 7, 10, 13, 16, 19] 

Now every third element starting from L[2]

>>> L[2::3] [2, 5, 8, 11, 14, 17] 

You can specify a negative step to go backwards

>>> L[::-1] [19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] 

You can also assign to this slice, but the value must have the same length as the slice you are replacing

>>> L[::3]=[0,0,0,0,0,0,0] >>> L [0, 1, 2, 0, 4, 5, 0, 7, 8, 0, 10, 11, 0, 13, 14, 0, 16, 17, 0, 19] 

Finally, you can delete every 3rd element like this

>>> del L[::3] >>> L [1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19] 
like image 35
John La Rooy Avatar answered Sep 28 '22 07:09

John La Rooy