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
# initializing list
test_list = [5, 6, 3, 2, 7, 1, 9, 10, 8]
# printing original list
print("The original list is : " + str(test_list))
# initializing skips
K = 3
res = []
for idx in range(0, K):
# 3rd arg. of slicing skips by K
res.append(test_list[idx::K])
# printing result
print("Stepped splitted List : " + str(res))
OutputThe 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
# initializing list
test_list = [5, 6, 3, 2, 7, 1, 9, 10, 8]
# printing original list
print("The original list is : " + str(test_list))
# initializing skips
K = 3
# list comprehension used as one liner
res = [test_list[idx::K] for idx in range(0, K)]
# printing result
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
# initializing list
test_list = [5, 6, 3, 2, 7, 1, 9, 10, 8]
# convert list to numpy array
arr = np.array(test_list)
# initializing skips
K = 3
# use numpy array slicing to split the array
res = [arr[i::K] for i in range(K)]
# convert the resulting arrays back to lists
res = [list(x) for x in res]
# printing result
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
# initializing list
test_list = [5, 6, 3, 2, 7, 1, 9, 10, 8]
# printing original list
print("The original list is : " + str(test_list))
# initializing skips
K = 3
# splitting the list using list comprehension and enumerate function
res = [[test_list[i] for i in range(len(test_list)) if idx == i % K] for idx, val in enumerate(test_list)]
# printing result
print("Stepped splitted List : " + str(res[:K]))
OutputThe 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 program to Convert a elements in a list of Tuples to Float Given a Tuple list, convert all possible convertible elements to float. Input : test_list = [("3", "Gfg"), ("1", "26.45")] Output : [(3.0, 'Gfg'), (1.0, 26.45)] Explanation : Numerical strings converted to floats. Input : test_list = [("3", "Gfg")] Output : [(3.0, 'Gfg')] Explanation : Numerical str
5 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 con
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
2 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 an
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 tu
3 min read
Python | Convert list into list of lists Given a list of strings, write a Python program to convert each element of the given list into a sublist. Thus, converting the whole list into a list of lists. Examples: Input : ['alice', 'bob', 'cara'] Output : [['alice'], ['bob'], ['cara']] Input : [101, 202, 303, 404, 505] Output : [[101], [202],
5 min read
Convert a List of Lists into Tree-like Dict - Python We are given a list of lists we need to convert it into tree-like dictionary. For example we are given a list of list li = [["a", "b", "c"], ["a", "b", "d"], ["x", "y"]] we need to convert it into tree like dict so that the output should be like {'a': {'b': {'c': {}, 'd': {}}}, 'x': {'y': {}}} .We c
5 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
Convert List of Tuples to Dictionary Value Lists - Python The task is to convert a list of tuples into a dictionary where the first element of each tuple serves as the key and the second element becomes the value. If a key appears multiple times in the list, its values should be grouped together in a list.For example, given the list li = [(1, 'gfg'), (1, '
4 min read