I have a list containing 100 items. How do I convert it to a 20*5 two-dimensional list? My code:
l = [2,3,1,...,77]
m = 20
n = 5
A couple of nested loops should do the trick:
result = []
for i in range(m):
row = []
for j in range(n):
row.append(l[i * n + j])
result.append(row)
l = [1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4]
n = 5
Using list comprehension
subLists = [l[i:i+n] for i in range(0, len(l), n)]
Using a generator
def make_sublists_generator(l, sublists_size):
for i in range(0, len(l), sublists_size):
yield l[i : i + sublists_size]
subLists = list(make_sublists_generator(l, n))
Both output the same
print(str(subLists))
[[1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [4, 4, 4, 4, 4]]
Note
It still works if the list does not have a size multiple of n, the last sublist will simply be shorter. You might want to check len(l)%sublists_size
at the start of the make_sublists
function if you want to raise an Exception