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

PythonServer Side ProgrammingProgramming

A list in python is normally a 1D list where the elements are listed one after another. But in a 2D list we have list nested inside the outer list. In this article we will see how to create a 2D list from a given 1D list. We also supply the values for the number of elements inside the 2D list to the program.

Using append and index

In this approach we will create a for loop to loop through each element in the 2D list and use it as an index for the new list to be created. We keep incrementing the index value by starting it at zero and adding it to the the element we receive from the 2D list.

Example

# Given list
listA = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']

# Length of 2D lists needed
len_2d = [ 2, 4]

#Declare empty new list
res = []
def convert(listA, len_2d):
   idx = 0
   for var_len in len_2d:
      res.append(listA[idx: idx + var_len])
      idx += var_len
convert(listA, len_2d)
print("The new 2D lis is: \n",res)

Running the above code gives us the following result −

Output

The new 2D lis is:
[[1, 2], [3, 4, 5, 6]]

Using islice

The islice function can be used to slice a given list with certain number of elements as required by the 2D list. So here week looked through each element of the 2D list and use that value 2 slice the original list. We need itertools package to use the islice function.

Example

from itertools import islice
# Given list
listA = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']

# Length of 2D lists needed
len_2d = [ 3, 2]

# Use islice
def convert(listA, len_2d):
   res = iter(listA)
   return [list(islice(res,i)) for i in len_2d]
res = [convert(listA, len_2d)]
print("The new 2D lis is: \n",res)

Running the above code gives us the following result −

Output

The new 2D lis is:
[[['Sun', 'Mon', 'Tue'], ['Wed', 'Thu']]]
raja
Published on 28-Dec-2020 15:50:56
Advertisements