What does colon ':' operator do in Python?

The : symbol is used for more than one purpose in Python

As slice operator with sequence −

The − operator slices a part from a sequence object such as list, tuple or string. It takes two arguments. First is the index of start of slice and second is index of end of slice. Both operands are optional. If first operand is omitted, it is 0 by default. If second is omitted, it is set to end of sequence.

>>> a=[1,2,3,4,5]
>>> a[1:3]
[2, 3]
>>> a[:3]
[1, 2, 3]
>>> a[2:]
[3, 4, 5]
>>> s='computer'
>>> s[:3]
>>> s[3:6]

The − symbol is also used to start an indent suite of statements in case of if, while, for, def and class statements

if expr:
while expr:
for x in sequence:
def  function1():

Updated on: 18-Jun-2020

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started