Skip to main content

Indices and Slices in Python

In Python, indices and slicing is used very commonly for retrieving an individual item or range of items from list, string, tuples. In this post, I'll cover on the basics of indexing using strings.

s="0123456789"

Syntax for using indexing/slicing is : [start:end:step], where start, end and stop are optional.
When using the slicing, start is the index from where to start printing and end is the first character which is NOT to be printed. Step decides the index increment value and if it is positive, then movement is done in forward direction.

# Example 1
s[::] 
=> will print 0 1 2 3 4 5 6 7 8 9
#In this case start will be 0 and stop will be len(s) and step will be 1.

# Example 2
s[1:5:1] 
=> will print 1 2 3 4

# Example 3
s[::-1] 
=> will print 9 8 7 6 5 4 3 2 1 0
#In this case start will be -1 and end will be -len(s)-1.

# Example 4
s[::-2] 
=> will print 9 7 5 3 1

Comments