Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create list of lists after every nth item [duplicate]

Tags:

python

In python how can I create a list of lists after every 5th item?

my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

Expected output:

new_list = [['a', 'b', 'c', 'd', 'e'], ['f', 'g', 'h', 'i', 'j']....]
like image 404
Hannan Avatar asked Oct 17 '25 23:10

Hannan


1 Answers

new_list = [my_list[i:i + 5] for i in xrange(0, len(my_list), 5)]

What's happening here is that takes chunks of data from 0 - 5, 5 - 10, etc. to create sub lists

like image 149
Usernamenotfound Avatar answered Oct 20 '25 13:10

Usernamenotfound