Home > Backend Development > Python Tutorial > How Can I Extend Python\'s zip() Function to Handle Iterables of Unequal Lengths?

How Can I Extend Python\'s zip() Function to Handle Iterables of Unequal Lengths?

Linda Hamilton
Release: 2024-11-27 17:56:13
Original
420 people have browsed it

How Can I Extend Python's zip() Function to Handle Iterables of Unequal Lengths?

Extending zip() Functionality: Padding to Longest Length

Python's built-in zip() function pairs elements from multiple iterables, but it truncates the result to the length of the shortest iterable. If you require a more comprehensive zip that pads with None values to align with the longest input, consider the following solutions:

Python 3: itertools.zip_longest

In Python 3, itertools provides the zip_longest() function. It expands the result list to match the length of the longest input.

import itertools
a = ['a1']
b = ['b1', 'b2', 'b3']
c = ['c1', 'c2']

list(itertools.zip_longest(a, b, c))
# [('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
Copy after login

You can specify a custom fill value using the fillvalue parameter:

list(itertools.zip_longest(a, b, c, fillvalue='foo'))
# [('a1', 'b1', 'c1'), ('foo', 'b2', 'c2'), ('foo', 'b3', 'foo')]
Copy after login

Python 2: itertools.izip_longest or map None

In Python 2, you can use itertools.izip_longest (introduced in Python 2.6) or employ map with None.

from itertools import izip_longest
a = ['a1']
b = ['b1', 'b2', 'b3']
c = ['c1', 'c2']

list(izip_longest(a, b, c))
# [('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]

map(None, a, b, c)
# [('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
Copy after login

The above is the detailed content of How Can I Extend Python\'s zip() Function to Handle Iterables of Unequal Lengths?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template