How to split a list into chunks in Python

5 Answers

0 votes
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

n = 3

result = [lst[i:i + n] for i in range(0, len(lst), n)]

print(result)



'''
run:

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18], [19]]

'''

 



answered Apr 18, 2021 by avibootz
0 votes
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

n = 3

chunk_list = lambda lst, n: [lst[i:i + n] for i in range(0, len(lst), n)]

result = chunk_list(lst, n)

print(result)



'''
run:

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18], [19]]

'''

 



answered Apr 18, 2021 by avibootz
0 votes
from itertools import islice

def chunk(lst, chunk_size):
    lst = iter(lst)
    return iter(lambda: tuple(islice(lst, chunk_size)), ())

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

for c in chunk(lst , 3):
    print(c)



'''
run:

(1, 2, 3)
(4, 5, 6)
(7, 8, 9)
(10, 11, 12)
(13, 14, 15)
(16, 17, 18)
(19,)

'''

 



answered Apr 18, 2021 by avibootz
0 votes
import numpy

n = numpy.arange(15)

lst = numpy.array_split(n, 4);

print(lst)




'''
run:

[array([0, 1, 2, 3]), array([4, 5, 6, 7]), array([ 8,  9, 10, 11]), array([12, 13, 14])]

'''

 



answered Apr 18, 2021 by avibootz
0 votes
def split_list(lst, n):  
    for i in range(0, len(lst), n): 
        yield lst[i:i + n] 

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

result = list(split_list(lst, 3)) 

print(result)



'''
run:

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18], [19]]

'''

 



answered Apr 18, 2021 by avibootz

Related questions

...