Saturday, December 28, 2024
Google search engine
HomeLanguagesPython | Variable list slicing

Python | Variable list slicing

The problem of slicing a list has been dealt earlier, but sometimes we need to perform the slicing in variable lengths according to the input given in other list. This problem has its potential application in web development. Let’s discuss certain ways in which this can be done. 

Method #1 : Using itertools.islice() + list comprehension The list comprehension can be used to iterate through the list and the component issue is solved using the islice function. 

Python3




# Python3 code to demonstrate
# variable length slicing
# using itertools.islice() + list comprehension
from itertools import islice
 
# initializing test list
test_list = [1, 5, 3, 7, 8, 10, 11, 16, 9, 12]
 
# initializing slice list
slice_list = [2, 1, 3, 4]
 
# printing original list
print("The original list : " + str(test_list))
 
# printing slice list
print("The slice list : " + str(slice_list))
 
# using itertools.islice() + list comprehension
# variable length slicing
temp = iter(test_list)
res = [list(islice(temp, part)) for part in slice_list]
 
# print result
print("The variable sliced list is : " + str(res))


Output : 

The original list : [1, 5, 3, 7, 8, 10, 11, 16, 9, 12]
The slice list : [2, 1, 3, 4]
The variable sliced list is : [[1, 5], [3], [7, 8, 10], [11, 16, 9, 12]]

Time complexity: O(n), where n is the length of test_list.
Auxiliary space: O(n), where n is the length of res list for storing the result.

  Method #2 : Using zip() + accumulate() + list slicing Apart from using the list comprehension to perform the task of binding, this method uses zip function to hold sublist element together, accumulate function joins the elements, and slicing is used to construct the required slicing. 

Python3




# Python3 code to demonstrate
# variable length slicing
# using zip() + accumulate() + list slicing
from itertools import accumulate
 
# initializing test list
test_list = [1, 5, 3, 7, 8, 10, 11, 16, 9, 12]
 
# initializing slice list
slice_list = [2, 1, 3, 4]
 
# printing original list
print("The original list : " + str(test_list))
 
# printing slice list
print("The slice list : " + str(slice_list))
 
# using zip() + accumulate() + list slicing
# variable length slicing
res = [test_list[i - j: i] for i, j in zip(accumulate(slice_list), slice_list)]
 
# print result
print("The variable sliced list is : " + str(res))


Output : 

The original list : [1, 5, 3, 7, 8, 10, 11, 16, 9, 12]
The slice list : [2, 1, 3, 4]
The variable sliced list is : [[1, 5], [3], [7, 8, 10], [11, 16, 9, 12]]

 Method #3 : Using looping and slicing

This approach iterates over the slice list and uses slicing to extract the corresponding sublists from the original list. The starting and ending indices for the slices are calculated using the current value in the slice list and the previous ending index. This solution has a time complexity of O(n), where n is the length of the slice list, and a space complexity of O(n), because it creates a new list to store the result.

Python3




# Python3 code to demonstrate
# variable length slicing
# Initialize the result list
result = []
# initializing test list
test_list = [1, 5, 3, 7, 8, 10, 11, 16, 9, 12]
# initializing slice list
slice_list = [2, 1, 3, 4]
# Set the starting index to 0
start = 0
# printing original list
print("The original list : " + str(test_list))
# printing slice list
print("The slice list : " + str(slice_list))
# Iterate over the slice list
for length in slice_list:
    # Calculate the ending index
    end = start + length
    # Append the slice to the result list
    result.append(test_list[start:end])
    # Set the starting index to the ending index
    start = end
 
print(result)
# This code is contributed by Edula Vinay Kumar Reddy


Output

The original list : [1, 5, 3, 7, 8, 10, 11, 16, 9, 12]
The slice list : [2, 1, 3, 4]
[[1, 5], [3], [7, 8, 10], [11, 16, 9, 12]]

Method #4 : Using list comprehension and zip() function

The idea is to use the zip() function to pair the slice_list with the starting index, and then use list comprehension to slice the test_list based on the paired values.

Step-by-step approach:

  • Uses a list comprehension and the zip() function to create a new list. The list comprehension iterates over the test_list using i as the starting index and j as the length of the slice.
  • In the zip() function, two arguments are passed. The first argument is a list created using list concatenation with [0] and the accumulated values of the slice_list. The accumulate function generates the accumulated sum of the slice_list. The second argument passed to zip() is the slice_list itself.
  • The resulting list is stored in the variable named result.
  • The result is printed.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate
# variable length slicing
from itertools import accumulate
 
# initializing test list
test_list = [1, 5, 3, 7, 8, 10, 11, 16, 9, 12]
# initializing slice list
slice_list = [2, 1, 3, 4]
# using list comprehension and zip() function
result = [test_list[i:i+j] for i,j in zip([0]+list(accumulate(slice_list)), slice_list)]
print(result)


Output

[[1, 5], [3], [7, 8, 10], [11, 16, 9, 12]]

Time complexity: O(n), where n is the length of test_list.
Auxiliary space: O(n), where n is the length of test_list (for storing the result list).

Method 5: Using numpy.split()

You can also solve the problem using the numpy.split() function. This method requires the installation of the NumPy library. 

  1. First, we import the NumPy library using the line import numpy as np.
  2. We initialize a test list test_list with some integer values: [1, 5, 3, 7, 8, 10, 11, 16, 9, 12].
  3. We also initialize a slice list slice_list with some integer values: [2, 1, 3, 4]. This will be used to define the lengths of the slices of test_list.
  4. We use the numpy.cumsum() function to compute the cumulative sum of the slice_list with a 0 added at the beginning of the list, which is done by [0] + slice_list. This gives us a new list starts which has the starting positions of each slice in the test_list.
  5. We use a list comprehension to extract the corresponding slice from the test_list using the starting positions computed in the previous step. The slice for each starting position is computed as test_list[starts[i]:starts[i+1]], where i is the index of the starting position. The result is a list of lists, where each sublist is a slice of test_list.
  6. Finally, we print the resulting list of lists, which is stored in the result variable.

Python3




import numpy as np
 
# initializing test list
test_list = [1, 5, 3, 7, 8, 10, 11, 16, 9, 12]
 
# initializing slice list
slice_list = [2, 1, 3, 4]
 
# Using numpy.split()
starts = np.cumsum([0] + slice_list)
result = [test_list[starts[i]:starts[i+1]] for i in range(len(starts)-1)]
 
print(result)


OUTPUT:

[[1, 5], [3], [7, 8, 10], [11, 16, 9, 12]]

The time complexity of this method is O(n), where n is the length of the test_list. 

Auxiliary space usage can be O(n+m), where n is the length of the test_list and m is the length of the slice_list.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments