MrAutodidact - 1 year ago 74
Python Question

# How do i make a list a list of list?

How do I get the items from the "list" shown below to look like the "new_list" which has the same amount of items in each list

``````list  = [1,0,1,1,1,0,1,0,          new_list = [[1,0,1,1,1,0,1,0],
0,0,0,1,1,0,0,0,                      [0,0,0,1,1,0,0,0],
1,1,1,0,0,1,0,0,                      [1,1,1,0,0,1,0,0],
0,0,0,0,0,1,1,1]              `       [0,0,0,0,0,1,1,1]]
``````

You can use `slicing` :

``````>>> l= [1,0,1,1,1,0,1,0,
...     0,0,0,1,1,0,0,0,
...     1,1,1,0,0,1,0,0,
...     0,0,0,0,0,1,1,1]

>>> [l[i:i+8] for i in range(0,len(l),8)]
[[1, 0, 1, 1, 1, 0, 1, 0],
[0, 0, 0, 1, 1, 0, 0, 0],
[1, 1, 1, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 1, 1, 1]]
``````

for check the consecutive 1 in your sub-lists :

``````>>> new=[l[i:i+8] for i in range(0,len(l),8)]
>>> [all(i==1 for i in sub) for sub in new]
[False, False, False, False]
>>> new.append([1,1,1,1,1,1,1])
>>> [all(i==1 for i in sub) for sub in new]
[False, False, False, False, True]
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download