Skip to main content

An embedding API accepts at most 100 texts per request. Split a list of texts into batches of that size. For example, 250 texts become three batches of 100, 100 and 50.

Coding rounds · Beginner 3

Short answer

Step through the list in jumps of the batch size and slice: [items[i:i + size] for i in range(0, len(items), size)]. Slicing past the end is safe, so the last batch is simply shorter. It is O(n) time. Use a generator to hold one batch at a time, or itertools.batched on Python 3.12 and later.

Deeper answer

First clarify the input. Ask whether it is a list in memory or a stream such as a file or a database cursor, whether order must be kept, and whether the limit is on item count only or also on total tokens per request.

For a list, the key expression is items[i:i + size] inside for i in range(0, len(items), size). A slice that runs past the end returns what is left, so no special case is needed for the last batch. Write it as a generator with yield so only one batch exists at a time. For a stream with no length, take it = iter(items) and repeat list(itertools.islice(it, size)) until it returns an empty list. On Python 3.12 or later, itertools.batched(items, size) does this and yields tuples.

The cost is O(n) time and O(size) extra memory with a generator. Test an empty list, a length that is an exact multiple of the size, a length smaller than the size, and a size of zero, which should raise a ValueError.

What a strong answer covers

Answer it out loud in the mock interview about 2 min

Follow-ups to expect

Common mistakes

Learn it

Write your own functions

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.