Slicing is a very common technique for analyzing data from a given list in Python. But for our analysis sometimes we need to create slices of a list for a specific range of values. For example we need to print 4 elements by skipping every 4 elements from the list. In this article we will see this concept of range slicing in Python.
Using range() and len()
We create a for loop to go through the entire length of the list but choose only the elements that satisfy the divisibility test. In the divisibility test we check for the value of the remainder for the kth element in the list. If the remainder is greater than or equal to the range value, we accept the element otherwise we do not.
Example
range_slicing = [6,9,11,15,20,24,29,36,39,43,47,52,56,70,73,79] print("The given list: ",range_slicing) # Range Value s = 4 # Using range and len result = [range_slicing[k] for k in range(len(range_slicing)) if k % (s * 2) >= s] print("\nThe list after range slicing: ",result)
Running the above code gives us the following result:
The given list: [6, 9, 11, 15, 20, 24, 29, 36, 39, 43, 47, 52, 56, 70, 73, 79] The list after range slicing: [20, 24, 29, 36, 56, 70, 73, 79]
Using enumeration
We apply the similar logic as in previous approach but instead of using range() and len() we simply apply enumerate(). Please note the last element in the list appears in the result because it satisfies the divisibility condition.
Example
range_slicing = [6,9,11,15,20,24,29,36,39,43,47,52,56,70,73,79] print("The given list: ",range_slicing) # Range value s2= 5 # Using Enumerate result_2 = [val for m, val in enumerate(range_slicing) if m % (s2 * 2) >= s2] print("\nThe list after range slicing: ",result_2)
Running the above code gives us the following result:
The given list: [6, 9, 11, 15, 20, 24, 29, 36, 39, 43, 47, 52, 56, 70, 73, 79] The list after range slicing: [24, 29, 36, 39, 43, 79]