Skip to content

Slice operator in Python | Basics

  • by

Slice operators are nothing bracket [] used with 3 values to slice string, tuple, or list in Python. The three-parameter is used in the slice operator is:-

  • start = include everything STARTING AT this idx (inclusive)
  • stop = include everything BEFORE this idx (exclusive)
  • step = (can be ommitted) difference between each idx in the sequence

Example Slice operator in Python

Simple example code slice string, tuple, and list in Python.

# string
name = "John"
print(name[:2])

# list
lst = [1, 2, 3, 4, 5, 6, 7, 8]
print(lst[5:9])

# tuple
tpl = (1, 2, 3, 4, 5, 6, 7, 8)
print(tpl[-4:-1])

Output:

Slice operator in Python

Cheat code for slice operator

a[start:stop] # items start through stop-1
a[start:] # items start through the rest of the array
a[:stop] # items from the beginning through stop-1
a[:] # a copy of the whole array

Do comment if you have any doubts or suggestions on this Python basic topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading