Python | Alternate range slicing in list
Last Updated :
18 Apr, 2023
List slicing is quite common utility in Python, one can easily slice certain elements from a list, but sometimes, we need to perform that task in non-contiguous manner and slice alternate ranges. Let’s discuss how this particular problem can be solved.
Method #1 : Using list comprehension List comprehension can be used to perform this particular task with ease as it can be used to run a loop and only filter the elements that leave a remainder more than half of target slice size multiplied by 2. By this way we can extract the sliced numbers in range alternatively.
Python3
test_list = [ 2 , 4 , 6 , 8 , 9 , 10 , 12 , 16 , 18 , 20 , 7 , 30 ]
print ("The original list : " + str (test_list))
N = 3
res = [test_list[i] for i in range ( len (test_list))
if i % (N * 2 ) > = N]
print ("The alternate range sliced list : " + str (res))
|
Output :
The original list : [2, 4, 6, 8, 9, 10, 12, 16, 18, 20, 7, 30]
The alternate range sliced list : [8, 9, 10, 20, 7, 30]
Time complexity: O(n), where n is the length of the list.
Auxiliary space: O(n), as a new list of size n is created to store the result of list comprehension.
Method #2 : Using enumerate() + list comprehension The list comprehension can also be combined with the enumerate function to perform this task. The advantage of using enumerate is that we can track of index along with the value and it’s more efficient and has lesser run-time than the above function.
Python3
test_list = [ 2 , 4 , 6 , 8 , 9 , 10 , 12 , 16 , 18 , 20 , 7 , 30 ]
print ("The original list : " + str (test_list))
N = 3
res = [val for i, val in enumerate (test_list)
if i % (N * 2 ) > = N]
print ("The alternate range sliced list : " + str (res))
|
Output :
The original list : [2, 4, 6, 8, 9, 10, 12, 16, 18, 20, 7, 30]
The alternate range sliced list : [8, 9, 10, 20, 7, 30]
Time complexity: O(n), where n is the length of the list, as the list comprehension and the enumerate() function both have linear time complexity.
Auxiliary space: O(n), as a new list of size n is created to hold the result of the list comprehension.
Method #3 : Using itertools +for loop
In this code, a list test_list is initialized with a set of values, and a variable N is defined as the range size for the alternate slicing.
Then, a loop is used to iterate over the elements of the test_list using the range() function. For each iteration, the index i is checked to see if it leaves a remainder of more than half of N when divided by N multiplied by 2. If the condition is true, the islice() function is used to slice the list and return only the element at the current index i. The result of the islice() function is then appended to the res list using the extend() method.
Finally, the res list is printed to the console.
Python3
from itertools import islice
test_list = [ 2 , 4 , 6 , 8 , 9 , 10 , 12 , 16 , 18 , 20 , 7 , 30 ]
N = 3
res = []
for i in range ( len (test_list)):
if i % (N * 2 ) > = N:
res.extend(islice(test_list, i, i + 1 ))
print ( "The alternate range sliced list:" , res)
|
Output
The alternate range sliced list: [8, 9, 10, 20, 7, 30]
The time complexity of this code is O(n), where n is the length of the test_list. This is because the loop iterates over the elements of the list once. The space complexity of this code is also O(n), because the res list is created and grows by one element for each iteration of the loop.
Method 4: Using filter() + enumerate() + method:
This approach uses the enumerate() function to get the index and value pairs of the test_list. The filter() function is then used to filter out the elements that do not satisfy the alternate range slicing condition. Finally, a list comprehension is used to extract the values from the filtered list.
Step-by-step approach:
- Initialize a list named test_list with some integer values.
- Print the original list using the print() function.
- Set a variable N equal to the desired range size.
- Use the enumerate() function to get the index and value pairs of the test_list.
- Use the filter() function to filter out the elements that do not satisfy the alternate range slicing condition.
- In this case, we want to keep the elements whose index modulo (N * 2) is greater than or equal to N.
- Convert the filtered values into a list using the list() function.
- Extract the values from the filtered list using a list comprehension.
- Print the resulting list using the print() function.
Below is the implementation of the above approach:
Python3
test_list = [ 2 , 4 , 6 , 8 , 9 , 10 , 12 , 16 , 18 , 20 , 7 , 30 ]
print ( "The original list : " + str (test_list))
N = 3
res = list ( filter ( lambda x: x[ 0 ] % (N * 2 ) > = N, enumerate (test_list)))
res = [x[ 1 ] for x in res]
print ( "The alternate range sliced list : " + str (res))
|
Output
The original list : [2, 4, 6, 8, 9, 10, 12, 16, 18, 20, 7, 30]
The alternate range sliced list : [8, 9, 10, 20, 7, 30]
Time complexity: O(n),
Auxiliary space: O(n), because it creates a new list to store the filtered values.
Similar Reads
Slicing range() function in Python
range() allows users to generate a series of numbers within a given range. Depending on how many arguments the user is passing to the function, the user can decide where that series of numbers will begin and end as well as how big the difference will be between one number and the next.range() takes
2 min read
Python - Specific Range Addition in List
Sometimes, while working with Python, we need to perform an edition in the Python list. And sometimes we need to perform this to a specific index range in it. This kind of application can have applications in many domains. Let us discuss certain ways in which this task can be performed. Method #1:
4 min read
Python - Ranged Maximum Element in String List
Sometimes, while working with Python data, we can have a problem in which we have data in form of String List and we require to find the maximum element in that data, but that also in a certain range of indices. This is quite peculiar problem but can have application in data domains. Let's discuss c
5 min read
Python | Decimal step range in list
Sometimes, while working with a Python list we can have a problem in which we require to populate the list in a range of decimals. Integral ranges are easier to handle using inbuilt constructs, but having a decimal value to provide to range value doesn't work. Let's discuss a way in which this probl
4 min read
Python - Extract Elements from Ranges in List
We are given a list and list containing tuples we need to extract element from ranges in tuples list. For example, n = [10, 20, 30, 40, 50, 60, 70, 80, 90] and r = [(1, 3), (5, 7)] (ranges) we need to extract elements so that output should be [[20, 30, 40], [60, 70, 80]]. Using List ComprehensionLis
3 min read
Python - Reverse Range in String List
Given a string list, reverse each element of string list from ith to jth index. Input : test_list = ["Geeksforgeeks", "Best", "Geeks"], i, j = 1, 2 Output : ['ee', 'es', 'ee'] Explanation : Range of strings are extracted. Input : test_list = ["Geeksforgeeks"], i, j = 1, 7 Output : ['eeksfor'] Explan
3 min read
Slice a 2D List in Python
Slicing a 2D list in Python is a common task when working with matrices, tables, or any other structured data. It allows you to extract specific portions of the list, making it easier to manipulate and analyze the data. In this article, we'll explore four simple and commonly used methods to slice a
4 min read
Python | Front and rear range deletion in a list
Sometimes, we require to shrink a list by deletion of its certain elements. One of the methods that is employed to perform this particular task is front and rear element deletion. It is a good utility whose solution can be useful to have. Let's discuss certain ways in which this can be performed. Me
7 min read
Python - Test if List contains elements in Range
Checking if a list contains elements within a specific range is a common problem. In this article, we will various approaches to test if elements of a list fall within a given range in Python. Let's start with a simple method to Test whether a list contains elements in a range. Using any() Function
3 min read
Python - Convert 2D list to 3D at K slicing
Sometimes, while working with Python lists, we can have a problem in which we need to convert a 2D list to 3D, at every Kth list. This type of problem is peculiar, but can have application in various data domains. Let's discuss certain ways in which this task can be performed. Input : test_list = [[
4 min read