Next / Previous / Contents / TCC Help System / NM Tech homepage

21.19. slice(): Create a slice instance

This function creates an instance of type slice. A slice instance I can be used to index a sequence S in an expression of the form S[I]. Here is the general form:

slice(start, limit, step)

The result is a slice that is equivalent to start:limit:step. Use None to get the default value for any of the three arguments.

Examples:

>>> r = range(9)
>>> r
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> r[::2]
[0, 2, 4, 6, 8]
>>> r[slice(None, None, 2)]
[0, 2, 4, 6, 8]
>>> r[3:7]
[3, 4, 5, 6]
>>> r[slice(3,7)]
[3, 4, 5, 6]
>>> r[1::2]
[1, 3, 5, 7]
>>> odds = slice(1, None, 2)
>>> r[odds]
[1, 3, 5, 7]
>>> 'roygbiv'[odds]
'ogi'