Python | Convert 1D list to 2D list of variable length
Given a 1D list ‘lst’ and list of variable lengths ‘var_lst’, write a Python program to convert the given 1D list to 2D list of given variable lengths.
Examples:
Input : lst = [1, 2, 3, 4, 5, 6]
var_lst = [1, 2, 3]
Output : [[1], [2, 3], [4, 5, 6]]
Input : lst = ['a', 'b', 'c', 'd', 'e']
var_lst = [3, 2]
Output : [['a', 'b', 'c'], ['d', 'e']]
Method #1 : List slicing
# Python3 program to Convert 1D # list to 2D list from itertools import islice def convert(lst, var_lst): idx = 0 for var_len in var_lst: yield lst[idx : idx + var_len] idx += var_len # Driver code lst = [1, 2, 3, 4, 5, 6] var_lst = [1, 2, 3] print(list(convert(lst, var_lst))) |
chevron_right
filter_none
Output:
[[1], [2, 3], [4, 5, 6]]
Method #2 : Using itertools.islice()
# Python3 program to Convert 1D # list to 2D list from itertools import islice def convert(lst, var_lst): it = iter(lst) return [list(islice(it, i)) for i in var_lst] # Driver code lst = [1, 2, 3, 4, 5, 6] var_lst = [1, 2, 3] print(convert(lst, var_lst)) |
chevron_right
filter_none
Output:
[[1], [2, 3], [4, 5, 6]]
Recommended Posts:
- Python | Convert list of string to list of list
- Python | Convert list of tuples to list of list
- Python | Convert list of string into sorted list of integer
- Python | Convert list of numerical string to list of Integers
- Python | Convert list of tuples to list of strings
- Python | Convert a nested list into a flat list
- Python | Convert a string representation of list into list
- Python | Convert list of strings to list of tuples
- Python | Convert list to indexed tuple list
- Python | Convert string enclosed list to list
- Python | Convert Integral list to tuple list
- Python | Find maximum length sub-list in a nested list
- Python | Convert given list into nested list
- Python | Convert list into list of lists
- Python | Convert list of tuples into list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



