Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,970 questions

51,912 answers

573 users

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

9 answers 798 views
1 answer 125 views
1 answer 132 views
1 answer 92 views
1 answer 92 views
...