Zip Iterables into Chunks in Python
In Python, the zip([iter(s)]n) function allows you to split a list into chunks of equal length. Here's how it works:
Explanation:
zip(*[iter(s)]*n):
Verbose Code Equivalent:
To understand the inner workings of zip(*[iter(s)]*n), let's write out the equivalent code with more verbose syntax:
s = [1, 2, 3, 4, 5, 6, 7, 8, 9] n = 3 # Create iterators for the list iter1 = iter(s) iter2 = iter(s) iter3 = iter(s) # Zip the iterators to create chunks chunks = zip(iter1, iter2, iter3) # Convert the generator to a list list_chunks = list(chunks)
In this verbose version:
Output:
The output of both the original and verbose code would be the same:
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
This demonstrates how zip(*[iter(s)]*n) conveniently splits a list into chunks by utilizing iterators and the zip function.
The above is the detailed content of How to Split a List into Equal Chunks Using zip(*[iter(s)]*n) in Python?. For more information, please follow other related articles on the PHP Chinese website!