Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paging python lists in slices of 4 items [duplicate]

Tags:

Possible Duplicate:
How do you split a list into evenly sized chunks in Python?

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

I need to pass blocks of these to a third party API that can only deal with 4 items at a time. I could do one at a time but it's a HTTP request and process for each go so I'd prefer to do it in the lowest possible number of queries.

What I'd like to do is chunk the list into blocks of four and submit each sub-block.

So from the above list, I'd expect:

[[1, 2, 3, 4], [5, 6, 7, 8], [9]] 
like image 822
Oli Avatar asked Oct 16 '10 17:10

Oli


People also ask

How do you repeat a list of elements in Python?

Using the * Operator The * operator can also be used to repeat elements of a list. When we multiply a list with any number using the * operator, it repeats the elements of the given list.

What is list manipulation in Python?

List is one of the simplest and most important data structures in Python. Lists are enclosed in square brackets [ ] and each item is separated by a comma. Lists are collections of items where each item in the list has an assigned index value. A list is mutable, meaning you can change its contents.


1 Answers

mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9]  print [mylist[i:i+4] for i in range(0, len(mylist), 4)] # Prints [[1, 2, 3, 4], [5, 6, 7, 8], [9]] 
like image 86
RichieHindle Avatar answered Jan 10 '23 14:01

RichieHindle