0

Say I have a list with 9 elements I want to split that list after every third element

["a", 1, 2, "b", 1, 2, "c", 1, 2]

Output:

["a", 1, 2]
["b", 1, 2]
["c", 1, 2]

Any suggestions toward this?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Check_mate
  • 45
  • 8
  • So basically you want groups of three right? – Aryan Dec 09 '20 at 11:05
  • 4
    Does this answer your question? [How do you split a list into evenly sized chunks?](https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks) – Axe319 Dec 09 '20 at 11:09

1 Answers1

1

Does this help with your question?

lst = ["a", 1, 2, "b", 1, 2, "c", 1, 2]

def chunks(lst, n):
    for i in range(0, len(lst), n):
        yield lst[i:i + n]

for i in chunks(lst, 3):
    print(i)

RESULT:

['a', 1, 2]
['b', 1, 2]
['c', 1, 2]

CREDIT: How do you split a list into evenly sized chunks?

If you any other queries or doubts feel free to ask to me I'll be there!
Happy Coding!

Aryan
  • 1,093
  • 9
  • 22
  • 3
    If you think this question has an answer somewhere else in this site - [flag it as duplicate](https://stackoverflow.com/help/privileges/flag-posts) instead of posting another answer as an answer... – Tomerikoo Dec 09 '20 at 11:35
  • Okay will do that – Aryan Dec 09 '20 at 12:04