Slice operator in Python | Basics

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

Exampel 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 and suggestions on this Python basic topic.

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.