Python program to convert a list into a list of lists using a step value
Last Updated :
21 Apr, 2023
Given a List, the task here is to write a python program that can split the list into list of lists using by a step value here denoted via K.
Input : test_list = [5, 6, 3, 2, 7, 1, 9, 10, 8], K = 3
Output : [[5, 2, 9], [6, 7, 10], [3, 1, 8]]
Explanation : 5, 2 and 9 are 0th, 3rd and 6th element respectively, and hence ( difference 3 ) grouped together.
Input : test_list = [5, 6, 3, 2, 7, 1], K = 3
Output : [[5, 2], [6, 7], [3, 1]]
Explanation : 5 and 2 are 0th and 3rd element respectively, and hence ( difference 3 ) grouped together.
Method 1: Using loop and slicing
In this, loop is employed to skip numbers as required, and each subsequent skipped sliced list is extracted using slicing and is appended to result.
Example:
Python3
test_list = [ 5 , 6 , 3 , 2 , 7 , 1 , 9 , 10 , 8 ]
print ( "The original list is : " + str (test_list))
K = 3
res = []
for idx in range ( 0 , K):
res.append(test_list[idx::K])
print ( "Stepped splitted List : " + str (res))
|
Output
The original list is : [5, 6, 3, 2, 7, 1, 9, 10, 8]
Stepped splitted List : [[5, 2, 9], [6, 7, 10], [3, 1, 8]]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 2: Using list comprehension and slicing
Similar to above method, only difference being usage of list comprehension for task of iteration instead of loop for shorthand alternative.
Step-by-step approach:
- Initialize a variable called K with the value 3.
- Use a list comprehension to create a new list called res that contains sublists of test_list. The sublist at index i in res is created by selecting every Kth element starting from index i in test_list.
- Print the resulting list.
Example:
Python3
test_list = [ 5 , 6 , 3 , 2 , 7 , 1 , 9 , 10 , 8 ]
print ( "The original list is : " + str (test_list))
K = 3
res = [test_list[idx::K] for idx in range ( 0 , K)]
print ( "Stepped splitted List : " + str (res))
|
Output:
The original list is : [5, 6, 3, 2, 7, 1, 9, 10, 8]
Stepped splitted List : [[5, 2, 9], [6, 7, 10], [3, 1, 8]]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 4: Using numpy array slicing
- Import the numpy library.
- Initialize the input list.
- Convert the input list to a numpy array.
- Initialize the skips variable.
- Use numpy array slicing to split the array into K chunks.
- Convert the resulting arrays back to Python lists.
- Store the sliced lists in the “res” variable.
- Print the resulting “res” variable.
Python3
import numpy as np
test_list = [ 5 , 6 , 3 , 2 , 7 , 1 , 9 , 10 , 8 ]
arr = np.array(test_list)
K = 3
res = [arr[i::K] for i in range (K)]
res = [ list (x) for x in res]
print ( "Stepped splitted List : " + str (res))
|
Output:
Stepped splitted List : [[5, 2, 9], [6, 7, 10], [3, 1, 8]]
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), where n is the length of the input list. This is because we need to store the sliced arrays in memory as separate lists.
Method 5: Using a list comprehension and the enumerate() function:
Python3
test_list = [ 5 , 6 , 3 , 2 , 7 , 1 , 9 , 10 , 8 ]
print ( "The original list is : " + str (test_list))
K = 3
res = [[test_list[i] for i in range ( len (test_list)) if idx = = i % K] for idx, val in enumerate (test_list)]
print ( "Stepped splitted List : " + str (res[:K]))
|
Output
The original list is : [5, 6, 3, 2, 7, 1, 9, 10, 8]
Stepped splitted List : [[5, 2, 9], [6, 7, 10], [3, 1, 8]]
Time complexity: O(N), where N is the length of the given list.
Auxiliary space: O(N/K), which is the space required to store the sliced sublists.
Similar Reads
Convert Set of Tuples to a List of Lists in Python
Sets and lists are two basic data structures in programming that have distinct uses. It is sometimes necessary to transform a collection of tuples into a list of lists. Each tuple is converted into a list throughout this procedure, and these lists are subsequently compiled into a single, bigger list
3 min read
Python - Convert a list into tuple of lists
When working with data structures in Python, there are times when we need to convert a list into a tuple of smaller lists. For example, given a list [1, 2, 3, 4, 5, 6], we may want to split it into a tuple of two lists like ([1, 2, 3], [4, 5, 6]). We will explore different methods to achieve this co
3 min read
Python - Convert Key-Value list Dictionary to List of Lists
We are given a key value list dictionary we need to convert it list of lists. For example we are given a dictionary a = {'name': 'Geeks', 'age': 8, 'city': 'Noida'} we need to convert this into list of lists so the output should be [['name', 'Geeks'], ['age', 25], ['city', 'Geeks']]. Using List Comp
3 min read
Python - Convert List of lists to list of Sets
We are given a list containing lists, and our task is to convert each sublist into a set. This helps remove duplicate elements within each sublist. For example, if we have: a = [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]] The output should be: [{1, 2}, {1, 2, 3}, {2}, {0}] Let's explore some method's t
2 min read
Python program to convert a byte string to a list of integers
We have to convert a byte string to a list of integers extracts the byte values (ASCII codes) from the byte string and stores them as integers in a list. For Example, we are having a byte string s=b"Hello" we need to write a program to convert this string to list of integers so the output should be
2 min read
Python | Convert List of lists to list of Strings
Interconversion of data is very popular nowadays and has many applications. In this scenario, we can have a problem in which we need to convert a list of lists, i.e matrix into list of strings. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + joi
4 min read
Python Program to Convert a list of multiple integers into a single integer
There are times when we need to combine multiple integers from a list into a single integer in Python. This operation is useful where concatenating numeric values is required. In this article, we will explore efficient ways to achieve this in Python. Using join()join() method is the most efficient a
2 min read
Python | Convert list of tuples to list of list
Converting list of tuples to list of lists in Python is a task where each tuple is transformed into list while preserving its elements. This operation is commonly used when we need to modify or work with the data in list format instead of tuples. Using numpyNumPy makes it easy to convert a list of t
3 min read
Python - Convert list of string into sorted list of integer
We are given a list of string a = ['3', '1', '4', '1', '5'] we need to convert all the given string data inside the list into int and sort them into ascending order so the output list becomes a = [1, 1, 3, 4, 5]. This can be achieved by first converting each string to an integer and then sorting the
3 min read
Python - Convert List of Integers to a List of Strings
We are given a list of integers and our task is to convert each integer into its string representation. For example, if we have a list like [1, 2, 3] then the output should be ['1', '2', '3']. In Python, there are multiple ways to do this efficiently, some of them are: using functions like map(), re
3 min read