Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Python by (19.9k points)

Suppose that I wish to chop up a list in python into equal-length pieces, is there an elegant way to do this? I don't want to try out the ordinary way of using an extra list and keeping a counter variable to cut the list at the right indices.

1 Answer

0 votes
by (25.1k points)
edited by

In python the most elegant way to do this would be to use a generator function that will keep slicing the list into another list of given size. For example:

def chunk_list(data, chunk_size):

  for i in range(0, len(data), chunk_size):

    yield data[i : i + n]

data = [x for x in range(1, 51)] # Data to chunk

for chunk in chunk_list(data, 5):

  print(chunk)

The generator function allows the caller to pause it's execution and return some value, in our case we are returning a small chunk of a list using the yield keyword.

Related questions

+5 votes
2 answers
asked May 29, 2019 in Python by Ritik (3.5k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...