-3

Trying to solve the following problem:

I have a large collection which I will represent by the following example list:

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

How do I splice up this list and return a sequence of delimited strings for every four elements in the list?

Desired output:

1, 2, 3, 4
5, 6, 7, 8
9, 10, 11, 12
13, 14, 15, 16
Jetals
  • 131
  • 1
  • 2
  • 10

1 Answers1

0

You can try this:

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

new_list = [l[i:i+4] for i in range(0, len(l), 4)]

Output:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
  • Answering low effort questions is encouraging low effort questions. – cs95 Sep 07 '17 at 23:14
  • 1
    Thanks for adding the link above and helping me find one of several other possible solutions. This comment here at the bottom, however, is altogether unnecessary and discouraging. – Jetals Sep 07 '17 at 23:38
  • @JamieStrausbaugh Glad to help! – Ajax1234 Sep 07 '17 at 23:41