Convert List into a List of Lists


Convert List into List of Lists

To convert a list of elements into a list of lists where the size of outer list is m and the length of each inner list is n, we can use the list comprehension as shown in the following.

[[myListx[i + (m+1)*j] for i in range(n)] for j in range(m) ]

Example

In the following program, we take a list myList with 12 elements, and transform this list into a list of lists where the length of outer list is 3, and the length of each inner list is 4.

Python Program

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

m = 3
n = 4

output = [[myList[i + (m+1)*j] for i in range(n)] for j in range(m) ]
print(output)

Output

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

Summary

In this Python Examples tutorial, we learned how to convert a given list into two-dimensional list or list of lists of specific size, using List Comprehension.