-1

Given a list, I want to group them into a nested list of size 5 in O(N) complexity WITHOUT SLICING.

Example an input of:

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

Output: [[5,2,4,7,6], [3,4,8,9,3], [2,1]]

without importing any packages as well.

So far, I've correctly done

def grouper(lst, size):
    groups = []
    for i in range(len(lst)%size + 1):
        groups.append([])
    

which returns [[],[],[]].

I've been trying to implement a while loop but I just can't find a way to keep count of the index of groups and index of list at the same time.

homies
  • 89
  • 10
  • This has been answered comprehensively in [What is the most "pythonic" way to iterate over a list in chunks?](https://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks) and [How do you split a list into evenly sized chunks?](https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks) – mkrieger1 Apr 10 '22 at 10:07
  • Without slicing, it's for example shown [in this existing answer](https://stackoverflow.com/a/59163343) or in [this other existing answer](https://stackoverflow.com/a/49456217). – mkrieger1 Apr 10 '22 at 10:13
  • Does this answer your question? [What is the most "pythonic" way to iterate over a list in chunks?](https://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks) – sahasrara62 Apr 10 '22 at 10:58

2 Answers2

2

You can use range function and provide the step ie 5 and using list slicing add all the elements in this step to result list.

>>> res =[]
>>> l = [5,2,4,7,6,3,4,8,9,3,2,1]
>>> for i in range(0, len(l), 5):
...     res.append(l[i:i+5])
... 
>>> res
[[5, 2, 4, 7, 6], [3, 4, 8, 9, 3], [2, 1]]

without list slicing, using stack.

>>> res = []
>>> l = [5,2,4,7,6,3,4,8,9,3,2,1]
>>> count = 0
>>> stack = []
>>> 
>>> for i in l:
...     if count==5:
...             res.append(stack)
...             stack=[]
...             count = 0
...     count+=1
...     stack.append(i)
... else:
...     if stack:
...             res.append(stack)
... 
>>> res
[[5, 2, 4, 7, 6], [3, 4, 8, 9, 3], [2, 1]]
sahasrara62
  • 10,069
  • 3
  • 29
  • 44
1

You can do it with list comprehensions

new_list = [old_list[i:i+x] for i in range(0, len(old_list), x)]

This will generate a list of lists, with every sublist having x elements.

Without slicing:

new_list = []
tmp = []
for i in range(len(old_list)):
   
    if not i % x and tmp:
        new_list.append(tmp)
        tmp = []

    tmp.append(old_list[i])

if i % x:
    new_list.append(tmp)