Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to chunk a list in Python 3?

I found the following code that is compatible with python2

from itertools import izip_longest def grouper(n, iterable, padvalue=None):   "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"   return izip_longest(*[iter(iterable)]*n, fillvalue=padvalue) 

However, this isn't working with Python 3. I get the following error

ImportError: cannot import name izip_longest 

Can someone help?

I'd like to convert my list of [1,2,3,4,5,6,7,8,9] to [[1,2,3],[4,5,6],[7,8,9]]

Edit

Now Python3 compatible

Code below is adapted from the selected answer. Simply change name from izip_longest to zip_longest.

from itertools import zip_longest def grouper(n, iterable, padvalue=None):   "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"   return zip_longest(*[iter(iterable)]*n, fillvalue=padvalue) 
like image 717
Mulan Avatar asked May 01 '11 18:05

Mulan


People also ask

How do you break a list in Python?

To split a list into n parts in Python, use the numpy. array_split() function. The np. split() function splits the array into multiple sub-arrays.

How do you split a list into 3 parts?

We define the chunkify function to split the lst list into n chunks. To do this, we use list comprehension to return slices of list with from index i to the end with n items in each chunk. Then we call chunkify with the list(range(13)) list and 3 to divide the list into 3 chunks.

How do you split a list in Python 3?

The split() method returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num.


1 Answers

In Python 3's itertools there is a function called zip_longest. It should do the same as izip_longest from Python 2.

Why the change in name? You might also notice that itertools.izip is now gone in Python 3 - that's because in Python 3, the zip built-in function now returns an iterator, whereas in Python 2 it returns a list. Since there's no need for the izip function, it also makes sense to rename the _longest variant for consistency.

like image 149
Ben James Avatar answered Sep 19 '22 15:09

Ben James