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) ]
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.
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)
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
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.
- Python List with First N Elements
- Python – How to Create an Empty List?
- How to Get the list of all Python keywords?
- How to Append List to Another List in Python? – list.extend(list)
- How to Reverse Python List?
- How to Check if Python List is Empty?
- Python List of Lists
- Shuffle Python List
- Python – Convert List to Dictionary
- Python – Check if Element is in List