4

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']....]
Hannan
  • 1,171
  • 6
  • 20
  • 39

1 Answers1

8
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

usernamenotfound
  • 1,540
  • 2
  • 11
  • 18