0

Given a list eg. [2,3,4,10,20,30,102] I need all possible chunks/sublists of length 3 as follows,

[[2, 3, 4], [3, 4, 10], [4, 10, 20], [10, 20, 30], [20, 30, 102]]
  • Possible duplicate of [How can I find all the subsets of a set, with exactly n elements?](http://stackoverflow.com/questions/374626/how-can-i-find-all-the-subsets-of-a-set-with-exactly-n-elements) – CaptainTrunky Apr 26 '17 at 03:53
  • @CaptainTrunky This is definitely not a duplicate of the linked question. This is a about consecutive subsequences rather than subsets. – Raymond Hettinger Apr 26 '17 at 04:10
  • I've retracted the flag from this question, sorry for the mistake. – CaptainTrunky Apr 26 '17 at 04:13
  • Possible duplicate of [Splitting a python list into a list of overlapping chunks](https://stackoverflow.com/questions/36586897/splitting-a-python-list-into-a-list-of-overlapping-chunks) – Georgy May 16 '18 at 09:50
  • 1
    @Georgy it is not though it is similar. –  May 16 '18 at 10:17

5 Answers5

2

This will do the job:

l= [2,3,4,10,20,30,102] 
res=[l[i:i+3] for i in range(len(l)-2)]
print(res)

This prints

[[2, 3, 4], [3, 4, 10], [4, 10, 20], [10, 20, 30], [20, 30, 102]]
Miriam Farber
  • 18,986
  • 14
  • 61
  • 76
1

this function will do the work and more

def chunks(sequence, length):
    sub_sequences = [sequence[offset:] 
                     for offset in range(length)]
    return zip(*sub_sequences)

for your example

list(chunks([2, 3, 4, 10, 20, 30, 102], length=3))

gives desired output

Azat Ibrakov
  • 9,998
  • 9
  • 38
  • 50
1

Use a list comprehension and a xrange operation will do you a favor.

Sample output

>>> a = [2,3,4,10,20,30,102]

>>> max_len = 3
>>> [ a[i-max_len: i] for i in xrange(max_len, len(a))]
[[2, 3, 4], [3, 4, 10], [4, 10, 20], [10, 20, 30]]

>>> max_len = 5
>>> [ a[i-max_len: i] for i in xrange(max_len, len(a))]
[[2, 3, 4, 10, 20], [3, 4, 10, 20, 30]]
go4big
  • 21
  • 4
0
arr = [2,3,4,10,20,30,102]
arr2 = arr
arr3 =[]
while (len(arr2) >= 3):
   arr4=arr2[:3]
   arr2 = arr2[1:]
   arr3.append(arr4)
print("Original List \n")
print(arr)
print("\n")
print("List with all the chunks \n")
print(arr3)
0

The easiest way is to use slicing:

>>> s = [2, 3, 4, 10, 20, 30, 102]
>>> [s[i:i+3] for i in range(0, len(s)-2)]
[[2, 3, 4], [3, 4, 10], [4, 10, 20], [10, 20, 30], [20, 30, 102]]
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485