Python - Convert 1D list to 2D list of variable length

A list in Python is normally a 1D list where the elements are listed one after another. But in a 2D list we have lists nested inside the outer list. In this article we will see how to create a 2D list from a given 1D list with variable-length sublists based on specified lengths.

Using Slicing with Index Tracking

In this approach we will create a for loop to iterate through each required length and use slicing to extract the appropriate elements from the 1D list. We keep track of the current index position and increment it by the length of each sublist ?

Example

# Given 1D list
days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']

# Length of 2D sublists needed
lengths = [2, 4, 1]

def convert_to_2d(source_list, sublist_lengths):
    result = []
    idx = 0
    for length in sublist_lengths:
        result.append(source_list[idx: idx + length])
        idx += length
    return result

result = convert_to_2d(days, lengths)
print("The new 2D list is:")
print(result)
The new 2D list is:
[['Sun', 'Mon'], ['Tue', 'Wed', 'Thu', 'Fri'], ['Sat']]

Using itertools.islice()

The islice() function can be used to slice a given list with a certain number of elements as required by each sublist. We iterate through each length value and use islice() to extract that many elements from the iterator ?

Example

from itertools import islice

# Given 1D list
days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']

# Length of 2D sublists needed
lengths = [3, 2, 2]

def convert_with_islice(source_list, sublist_lengths):
    iterator = iter(source_list)
    return [list(islice(iterator, length)) for length in sublist_lengths]

result = convert_with_islice(days, lengths)
print("The new 2D list is:")
print(result)
The new 2D list is:
[['Sun', 'Mon', 'Tue'], ['Wed', 'Thu'], ['Fri', 'Sat']]

Comparison

Method Complexity Memory Usage Best For
Slicing with Index O(n) Creates new lists Simple, readable code
islice() O(n) Memory efficient Large datasets

Conclusion

Both methods effectively convert a 1D list to a 2D list with variable-length sublists. Use slicing for simplicity and readability, or islice() for better memory efficiency with large datasets.

Updated on: 2026-03-15T18:34:23+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements