Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split an array into chunks of a given length in python? [duplicate]

Tags:

python

What is the fastest and shortest method to turn this:

ids = [1, 2, 3, 4, 5, 6, 7, 8, 9]

for example into this:

ids = [[1, 2], [3, 4], [5, 6], [7, 8], [9]]

by giving the input 2 as the fixed length.

Of course there are some easy ways to make this but none of them occur to me as fast or pretty.

like image 246
StrangeGirlMurph Avatar asked Jun 07 '26 14:06

StrangeGirlMurph


1 Answers

Why don't you try out a list comprehension?

Example:

[ids[i:i+2] for i in range(0,len(ids),2)]

Output:

[[1, 2], [3, 4], [5, 6], [7, 8], [9]]

like image 73
Spiros Gkogkas Avatar answered Jun 10 '26 03:06

Spiros Gkogkas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!