Python slice() Function

The slice() function in Python returns slice object. Basically it is used when we need to slice an object. For example:

a = [12, 23, 34, 45, 56, 67, 78, 89]
x = slice(4)
print(type(x))

The output is:

<class 'slice'>

Python slice() Function Syntax

The syntax of slice() function in Python, is:

slice(startIndex, stopIndex, step)

where:

  • startIndex - refers to an integer value, that specifies from which index, the slicing to start
  • stopIndex - refers to an integer value, that specifies the index number at where the slice to stop
  • step - refers to an integer value, that specifies the step of slicing. For example, if 4 is given to step, then every fourth element will get returned

Note - The startIndex and step parameters are optional.

Note - The default value of startIndex is 0, where step is 1

Python slice() Function Example

Here is an example of slice() function in Python:

a = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

x = slice(4)
print(a[x])

x = slice(1, 4)
print(a[x])

x = slice(1, 8, 3)
print(a[x])

str = "Python Programming is Fun!"
sliceOb = slice(6)
print(str[sliceOb])

The output is:

[11, 12, 13, 14]
[12, 13, 14]
[12, 15, 18]
Python

Now the question is, what if there are multiple iterators available before the slice() function ?
Let's find out, using the program given below:

a = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
b = [21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
c = (31, 32, 33, 34, 35, 36, 37, 38, 39, 40)

x = slice(4)
print(a[x])
print(b[x])
print(c[x])

The output produced by this program is:

[11, 12, 13, 14]
[21, 22, 23, 24]
(31, 32, 33, 34)

Means that every object, that is a, b, and c are sliced and the slice object is x that holds the first four elements of respective object.

Use slice() to Slice using Negative Indexing - Backward Slicing

Here is an example, shows the use of slice() function to slice an object from backward, using negative indexing.

str = "Python Programming is Fun!"
sliceOb = slice(-1, -5, -1)
print(str[sliceOb])

The output is:

!nuF

Note - The -1 index number, refers to the last item.

Python Online Test


« Previous Function Next Function »



Like/Share Us on Facebook 😋