Start Stop Step Python | slice() Parameters

The slice method has 3 notations – Start Stop Step in Python. slice(start: stop[: step]) is an object usually containing a portion of a sequence. This function can be used to slice tuples, arrays, sentences, and lists.

Here is the syntax of the slice() method.

slice(start, stop, step)
  • start (optional)- Starting index value where the slicing of the object starts. Default to 0 if not provided.
  • stop – Index value until which the slicing takes place.
  • step (optional) – Index value steps between each index for slicing. Defaults to 1 if not provided.

Example Start Stop Step Python

Here is a Python example of the slice method with the Start, Stop, and Step Arguments (Parameters).

If the only stop is provided, it generates a portion of sequence from index 0 till stop

a = [1, 2, 3, 4, 5, 6, 7, 8]
print(a[:5])

Output:

Start Stop Step Python

If only start is provided, it generates a portion of the sequence after an index starts till the last element.

a = [1, 2, 3, 4, 5, 6, 7, 8]
print(a[3:])

Output: [4, 5, 6, 7, 8]

If both start and stop are provided, it generates a portion of the sequence after the index starts till the stop.

a = [1, 2, 3, 4, 5, 6, 7, 8]
print(a[3:5])

Output: [4, 5]

If all three starts, stop, and step are provided, it generates a portion of the sequence after index starts till stop with an increment of index step.

a = [1, 2, 3, 4, 5, 6, 7, 8]
print(a[3:7:2])

Output: [4, 6]

Do comment if you have any doubts and suggestions on these Python slice notations.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.