In the last tutorial, I explained how the method slice() and extended slice works in Python
But while I was writing the tutorial I always thought “it was not enough. I should be writing a new post which will have various examples of slice and extended slice for better understanding”
So before spending to much time let me ask some questions which will be asked to you in examinations or interviews
1. Output every alternate item in the given list using slice() including the first element in the list
myList = [3,6,1,-2,-4,19,2,8,3,2,9,10,-23,34] slice1 = slice(0,len(myList),2) print(myList[slice1]) # Outputs [3, 1, -4, 2, 3, 9, -23]
2. Output every alternate character in the given string using slice() excluding the first character in the list
myString = 'This is a sample string used in slice' print(myString[2:len(myString):2]) # Outputs 'i sasml tigue nsie' as a string
3. Output the slice of the given list beginning at 3rd position till 5th element from the start position
myTuple = (0,1,2,3,4,5,6,7,8,9,10,11) start = 3 end = 5 slice1 = slice(3,start+end,1) print(myTuple[slice1]) # Outputs (3, 4, 5, 6, 7)
4. Reverse a list or a string using the slice
myList = [10,11,12,13,14,15] print(myList[len(myList):-(len(myList)+1):-1]) # Outputs [15, 14, 13, 12, 11, 10] myString = "!eM esreveR" print(myString[len(myString):-(len(myString)+1):-1]) #Outputs 'Reverse Me!'
5. Output last N number of items in a list using the slice
myTuple = (1,2,3,4,5,6,7,8,9,10) N = 6 print(myTuple[len(myTuple)-N:len(myTuple)]) # Outputs (5, 6, 7, 8, 9, 10) myString = "The Sample String to get a random slice" N = 12 print(myString[len(myString)-N:len(myString)]) # Outputs 'random slice'
6. Output last N number of items in a list using the slice in reverse order
myTuple = (1,2,3,4,5,6,7,8,9,10) N = 6 print(myTuple[len(myTuple):len(myTuple)-(N+1):-1]) # Outputs (10, 9, 8, 7, 6, 5) myString = "The Sample String to get a random slice" N = 12 print(myString[len(myString):len(myString)-(N+1):-1]) # Output 'ecils modnar'
7. Output all even numbers between N1 to N2 where N1 is even number (Please note these can be done using range() method as well)
N1 = 20 N2 = 35 myList = [] for n in range(N1,N2): myList.append(n) slice1 = slice(0,len(myList),2) print(myList[slice1]) # Outputs [20, 22, 24, 26, 28, 30, 32, 34]
8. Example of the nested slice
N1 = 0 N2 = 100 myList = [] for n in range(N1,N2,10): myList.append(n) # myList -> [0,10,20,30,40,50,60,70,80,90] print(myList[::1][::2]) # Outputs [0, 20, 40, 60, 80]
One Reply to “Python Slice Examples”