Skip to content
Related Articles

Related Articles

Python | Reshape a list according to given multi list
  • Last Updated : 25 Apr, 2019
GeeksforGeeks - Summer Carnival Banner

Given two lists, a single dimensional and a multidimensional list, write Python program to reshape the single dimensional list according to the length of multidimensional list.

Examples:

Input : list1 = [[1], [2, 3], [4, 5, 6]]
        list2 = ['a', 'b', 'c', 'd', 'e', 'f']
Output : [['a'], ['b', 'c'], ['d', 'e', 'f']]

Input : list1 = [[8, 2, 5], [1], [12, 4, 0, 24]]
        list2 = ['m', 'n', 'o', 'p', 'q', 'r', 's', 't']
Output : [['m', 'n', 'o'], ['p'], ['q', 'r', 's', 't']]

 
Method #1 : Using extended slices

A simple and naive method is to use a for loop and Python extended slices to append each sublist of list2 to a variable ‘res’.




# Python3 program to reshape a list 
# according to multidimensional list
          
def reshape(lst1, lst2):
    last = 0
    res = []
    for ele in list1:
        res.append(list2[last : last + len(ele)])
        last += len(ele)
          
    return res
  
# Driver code
list1 = [[1], [2, 3], [4, 5, 6]]
list2 = ['a', 'b', 'c', 'd', 'e', 'f']
print(reshape(list1, list2))
Output:



[['a'], ['b', 'c'], ['d', 'e', 'f']]

 
Method #2 : islice from itertools module

Another method is to use islice function from itertools module. islice selectively prints the values mentioned in its iterable container. Thus, we yield slices of list2 according to list1 and append it to variable ‘res’.




# Python3 program to reshape a list 
# according to multidimensional list
from itertools import islice
  
def yieldSublist(lst1, lst2):
    iter2 = iter(lst2)
    for sublist1 in lst1:
        sublist2 = list(islice(iter2, len(sublist1)))
        yield sublist2
          
def reshape(lst1, lst2):
    res = list()
    for sub2 in yieldSublist(list1, list2):
        res.append(sub2)
          
    return res
  
# Driver code
list1 = [[1], [2, 3], [4, 5, 6]]
list2 = ['a', 'b', 'c', 'd', 'e', 'f']
print(reshape(list1, list2))
Output:
[['a'], ['b', 'c'], ['d', 'e', 'f']]

 

Method #3 : Python iterator with list comprehension

The iter() method returns an iterator for list2 and save it in variable ‘iterator’. Now using list comprehension reshape list2 according to list1.




# Python3 program to reshape a list 
# according to multidimensional list
  
def reshape(lst1, lst2):
    iterator = iter(lst2)
    return [[next(iterator) for _ in sublist] 
                         for sublist in lst1]
  
# Driver code
list1 = [[1], [2, 3], [4, 5, 6]]
list2 = ['a', 'b', 'c', 'd', 'e', 'f']
print(reshape(list1, list2))
Output:
[['a'], ['b', 'c'], ['d', 'e', 'f']]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :