Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
Filter by Categories
About Article
Analyze Data
Archive
Best Practices
Better Outputs
Blog
Code Optimization
Code Quality
Command Line
Daily tips
Dashboard
Data Analysis & Manipulation
Data Engineer
Data Visualization
DataFrame
Delta Lake
DevOps
DuckDB
Environment Management
Feature Engineer
Git
Jupyter Notebook
LLM
LLM
Machine Learning
Machine Learning
Machine Learning & AI
Manage Data
MLOps
Natural Language Processing
NumPy
Pandas
Polars
PySpark
Python Tips
Python Utilities
Python Utilities
Scrape Data
SQL
Testing
Time Series
Tools
Visualization
Visualization & Reporting
Workflow & Automation
Workflow Automation

zip_longest: Handling Iterables of Different Lengths in Python

Table of Contents

zip_longest: Handling Iterables of Different Lengths in Python

When working with iterables in Python, you may need to aggregate elements from multiple iterables. The built-in zip function can do this, but it stops when the shortest iterable is exhausted, potentially omitting pairs of elements if the iterables have different lengths.

Let’s consider an example:

fruits = ["apple", "orange", "grape"]
prices = [1, 2]

If we use zip to aggregate these iterables, we’ll get:

list(zip(fruits, prices))

Output:

[('apple', 1), ('orange', 2)]

As you can see, the third element of the fruits iterable (“grape”) is not included in the output because there is no corresponding element in the prices iterable.

To overcome this limitation, we can use the zip_longest function from the itertools module. This function aggregates iterables of different lengths by filling missing values with a specified fillvalue.

Here’s how we can use zip_longest to aggregate our fruits and prices iterables:

from itertools import zip_longest

list(zip_longest(fruits, prices, fillvalue="-"))

Output:

[('apple', 1), ('orange', 2), ('grape', '-')]

In this example, the fillvalue is set to "-", which means that missing values in the prices iterable are replaced with a hyphen.

Leave a Comment

Your email address will not be published. Required fields are marked *

0
    0
    Your Cart
    Your cart is empty
    Scroll to Top

    Work with Khuyen Tran

    Work with Khuyen Tran