-1

Here is what I have:

mylist = [1, 2, 7, 11, 8, 55, 89, 1, 3, 8]

How can I get this broken down by 5 to the list of lists.

The desired outcome is: [[1, 2, 7, 11, 8], [2, 7, 11, 8, 55], [7, 11, 8, 55, 89],[11, 8, 55, 89, 1], [8, 55, 89, 1, 3], [55, 89, 1, 3, 8]]

Here is what I've tried:

indices = [0,1,2]
for i in indices:
   new.append(mylist [i])
   indices = [x+1 for x in indices]
   print(indices)

Thank you in advance.

Andre
  • 247
  • 2
  • 6

2 Answers2

1

It is easy to use a list comprehension:

>>> mylist = [1, 2, 7, 11, 8, 55, 89, 1, 3, 8]

>>> [mylist[i:i+5] for i in range(6)]
[[1, 2, 7, 11, 8], [2, 7, 11, 8, 55], [7, 11, 8, 55, 89], [11, 8, 55, 89, 1], [8, 55, 89, 1, 3], [55, 89, 1, 3, 8]]
AboAmmar
  • 5,439
  • 2
  • 13
  • 24
1

The following two options are available.

  1. List Generative
mylist = [1, 2, 7, 11, 8, 55, 89, 1, 3, 8]
res = [mylist[i:i+5] for i in range(0, len(mylist)-4)]
  1. a loop, since it is constructed sequentially and can simply exit the loop once the length is not satisfied (see also the previous approach for a limit on the length of the loop)
mylist = [1, 2, 7, 11, 8, 55, 89, 1, 3, 8]
new = []
for i in range(0, len(mylist)):
    if len(mylist[i:i+5]) == 5:
        new.append(mylist[i:i+5])
    else:
        break
maya
  • 1,029
  • 1
  • 2
  • 7