ScanSkill

slice

This slice() function returns a sliced object.

Syntax

slice(start, stop[, step])

Here,

  • start: Required if start is used. Starting index. Default is none.
  • stop: Required. Last item plus one returned by the slice. The slicing stops at stop-1.
  • step: Optional. Value of the step. Default is none.

Note: When there are multiple arguments that are all of the same length, zip() is similar to map() with an initial argument of None. With a single sequence argument, it returns a list of 1-tuples. With no arguments, it returns an empty list.

Examples

  • Slice object using slice()
>>> # It contains indices (0, 1, 2, 3, 4, 5, 6)
>>> slice(7)
slice(None, 7, None)

>>> # It contains indices (1, 4)
>>> slice(1, 7, 3)
slice(1, 7, 3)
  • With string slicing
# Without start and stop parameter
>>> string1 = "cloudyfox"
>>> string1[slice(5)]
'cloud'
 
>>> # With start and step parameter
>>> string1 = "cloudyfox"
>>> string1[slice(1, 7, 2)]
'luy'
  • With tuple and list
>>> tuple1 = ('c', 'l', 'o', 'u', 'd', 'y')
>>> list1 = ['c', 'l', 'o', 'u', 'd', 'y']
>>> list1[slice(0, 5, 2)]
['c', 'o', 'd']
>>> list1[slice(1, 5, 2)]
['l', 'u']