Reading Time: 1 minutes
Slicing in Python
Slicing means getting a portion of an ordered sequence. An ordered sequence is a sequence whose elements can be accessed using indexes. Examples of ordered sequences are strings, lists, tuples. Here's how you can slice strings in Python.
>>> originalString = "magnanimous" >>> arrayRepresentationOfOriginalString = ''' # for understanding indexes used later 0 1 2 3 4 5 6 7 8 9 10 _ _ _ _ _ _ _ _ _ _ _ | | | | | | | | | | | | | m | a | g | n | a | n | i | m | o | u | s | | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 ''' >>> st = originalString # for easy reference >>> st[1:5] # st[x:y] gives us a string starting with st[x] and ending with st[y-1] 'agna' >>> st[-5:-1] # -5 is actually 6 and -1 is actually 10, so this becomes st[6:10] 'imou' >>> st[1:5:1] # st[x:y:z] gives us a string starting with st[x], with a step over size of 1, ending with st[y-1] 'agna' >>> st[1:5:2] # starting at index 1, ending with index 5-1, with a difference of 2 between the indexes of characters 'an' >>> st[5:1:-1] # FOR NEGATIVE STEP SIZE: begin at index 5, move in the opposite direction i.e. left, finish at index 1 + 1. 'nang' >>> st[-5:-8:-1] 'ina' >>> st[:5] # select everything from index 0 to 5-1 'magna' >>> st[5:] # select everything from index 5 till the end of the originalString 'nimous' >>> st[:] # gives the originalString itself 'magnanimous' # Slicing takes characters from left to right of a string, unless you specify a negative step size. What this means is that by default, the first number should should be the index of a character on the left of character whose index is denoted by the second number, UNLESS a negative step size is specified, in which case, the first number should be the index of a character on the right of the character whose index is denoted by the second number. Not confusing, right?
Expand for slicing scenarios in lists, tuples, sets & dictionaries.
####################### # SLICING A LIST: [:] # ####################### # Slicing in lists works the same way as it does in strings. The indices start from 0. Slicing DOES NOT hamper the original list, unless you assign the sliced list to the original variable. # [:] gives the original list print(list1[:]) # ['one', 2, 'three', 'IV'] # [x:] gives a list starting from element at index 1 till the end of the list print(list1[1:]) # [2, 'three', 'IV'] # [:x] gives a list from the beginning of the original list till the element at index(x - 1). print(list1[:3]) # ['one', 2, 'three'] # [x:y] gives a list from element at index x till element at index (y - 1). print(list1[1:3]) # [2, 'three'] # [x:y:z] gives a list from element at index x till the element at index y, picking every zth element. list10 = range(0, 10) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(list10[::3]) # [0, 3, 6, 9] # Negative step size also works. In this case, the element represented by first index you specify has to be on the right of the element represented by the second index, in the original list. Else, it will return an empty list. An exception of this would be [::-z] which will iterate the list from the rear end by default. list10[10:0:-3] # [9, 6, 3] list10[::-3] # [9, 6, 3, 0] # the default value of the second index is -(len + 1) when the step/stride is negative. Note that -11 in the second argument will mean a slice from the end to index -10, which is element 0 in the list. In the above expression, slice is till 0 + 1 i.e. index 1. # You can of course use negative indexes as well, I'll leave that to you to explore. Comment below if you run into any problem. ######################## # SLICING A TUPLE: [:] # ######################## # Slicing DOES NOT hamper the original tuple, unless you assign the sliced list to the original variable. tuple1 = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) # [:] gives the original tuple print(tuple1[:]) # (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) # [x:] gives a tuple starting from element at index 1 till the end of the tuple print(tuple1[1:]) # (1, 2, 3, 4, 5, 6, 7, 8, 9) # [:x] gives a tuple from the beginning of the original tuple till the element at index(x - 1). print(tuple1[:3]) # (0, 1, 2) # [x:y] gives a tuple from element at index x till element at index (y - 1). print(tuple1[1:3]) # (1, 2) # [x:y:z] gives a tuple from element at index x till the element at index y, picking every zth element. print(tuple1[::3]) # (0, 3, 6, 9) # Negative step size also works. In this case, the element represented by first index you specify has to be on the right of the element represented by the second index, in the original tuple. Else, it will return an empty tuple. An exception of this would be [::-z] which will iterate the tuple from the rear end by default. tuple1[10:0:-3] # (9, 6, 3) tuple1[::-3] # (9, 6, 3, 0) # the default value of the second index is -(len + 1) when the step/stride is negative. Note that -11 in the second argument will mean a slice from the end to index -10, which is element 0 in the list. In the above expression, slice is till 0 + 1 i.e. index 1. # You can of course use negative indexes as well, I'll leave that to you to explore. Comment below if you run into any problem. ############################# # SLICING A DICTIONARY: n/a # ############################# # Slicing a python dictionary is not a valid operation, since dictionaries are not index-based data structures like lists. If you try to slice a dictionary, python throws: TypeError: unhashable type: 'slice' ######################################################### # SLICING A SET: not supported since a set is unordered # ######################################################### >>> setOfAnimals = {"cat", "dog", "elephant", "snake"} >>> setOfAnimals[:] # Traceback info TypeError: 'set' object is not subscriptable