2 ms·
Drat, the only one I don't know is [0:10:2]. I guess it's back to The Python Tutorial for me. http://docs.python.org/tutorial/ http://docs.python.org/tutorial
by palish 18y ago
Drat, the only one I don't know is [0:10:2]. I guess it's back to The Python Tutorial for me. http://docs.python.org/tutorial/ http://docs.python.org/tutorial/
Followup: The tutorial didn't seem to mention what [x:y:z] does, so I checked:
>>> range(15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> range(15)[0:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(15)[0:10:2]
[0, 2, 4, 6, 8]
>>> range(15)[0:10:3]
[0, 3, 6, 9]
So the third argument is the number of elements to skip (minus one) between each item in the new sequence. Neat.
- nadim 18y agoI also found this: http://www.python.org/doc/2.3.5/whatsnew/section-slices.html http://www.python.org/doc/2.3.5/whatsnew/section-slices.html These are "extended slices" and the third argument is the step. This link also explores deletion and the __getitem__ method: One can also now pass slice objects to the __getitem__ methods of the built-in sequences: >>> range(10).__getitem__(slice(0, 5, 2)) [0, 2, 4] Or use slice objects directly in subscripts: >>> range(10)[slice(0, 5, 2)] [0, 2, 4]