Home >Backend Development >Python Tutorial >How to Split a List into Equal Chunks Using zip(*[iter(s)]*n) in Python?

How to Split a List into Equal Chunks Using zip(*[iter(s)]*n) in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-20 13:03:21470browse

How to Split a List into Equal Chunks Using zip(*[iter(s)]*n) in Python?

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:

  1. iter(s): This creates an iterator over the input list s.
  2. [iter(s)]*n: This creates a list of n iterators, each iterating over the same list s.
  3. zip(*[iter(s)]*n):

    • The * unpacks the list of iterators into individual arguments for the zip() function.
    • zip() takes a sequence of iterators and combines their elements into tuples.

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:

  1. We create three iterators for the same list s.
  2. We pass these iterators to zip() using unpacking.
  3. The resulting generator expression is converted to a list to produce the chunks.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn