4 ms·
Yes. I’ve written explicit code that needed this 100s of times.
by philshem 3y ago
Yes. I’ve written explicit code that needed this 100s of times.
- intalentive 3y agoYeah I've memorized it by now: for i in range(len(lst) // batch_size + 1): batch = lst[i * batch_size : (i + 1) * batch_size]
- hddqsb 3y agoYou have a minor bug -- when len(lst) is a multiple of batch_size, this will have an extra iteration at the end with an empty batch. The fixed version is `range((len(lst) + batch_size - 1) // batch_size)`, which emulates `ceil(len(lst) / batch_size)`. Yet more proof that this should be part of stdlib :) Personally I think I'd actually write it like this: for i in range(0, len(lst), batch_size): batch = lst[i:i+batch_size] The docs give another pretty nice implementation using iter() and islice() in a loop (but it uses the walrus operator `:=` so it requires Python 3.8+ as written).
- rossant 3y agoBlatant reason why a native solution was long overdue.
- deleted 3y ago[deleted]