1. Home
  2. Blog
  3. Software Development

Software Development

Python zip() Explained: Loop Two Lists at Once, Unzip, strict=True and Traps

Python zip() takes two or more iterables and pairs their items by position, so you can loop over several lists at once. Learn how to build dictionaries, unzip with *, catch length mismatches with strict=True, keep extra items with zip_longest, and avoid the traps that silently lose data.

9 min read
Python zip() explained with examples

Key takeaways

  • Python zip pairs items by position: zip(names, scores) gives (name, score) tuples.
  • It stops at the shortest input without warning; in our test a 3-item and a 2-item list produced only 2 pairs.
  • strict=True (Python 3.10+) turns that silent loss into a ValueError; zip_longest keeps every item instead.
  • zip(*pairs) unzips and also transposes rows and columns.

Two lists that belong together, such as names and scores, dates and prices or keys and values, are everywhere in real code. Looping over them by index works but reads poorly and breaks easily. Python zip is the built-in that walks them side by side. Every output in this guide comes from code we ran on Python 3.13.6.

Quick answer

names = ["Asha", "Ravi", "Li"]
scores = [91, 78, 85]
for name, score in zip(names, scores):
    print(name, score)
Asha 91
Ravi 78
Li 85

Each pass gives one item from each list, matched by position. If you also need the position, combine it with enumerate(): for i, (name, score) in enumerate(zip(names, scores), 1).

How zip() works

zip() accepts any number of iterables: lists, tuples, strings, ranges, files or generators. It returns an iterator of tuples, where the first tuple holds the first item of every input, the second holds the second items, and so on:

print(list(zip(names, scores)))
print(list(zip(range(3), "abc", [True, False, True])))
[('Asha', 91), ('Ravi', 78), ('Li', 85)]
[(0, 'a', True), (1, 'b', False), (2, 'c', True)]

Two edge cases are worth knowing: zip() with no arguments gives an empty result, and zip(names) with one argument gives one-item tuples such as ('Asha',).

Build a dictionary from two lists

print(dict(zip(names, scores)))
{'Asha': 91, 'Ravi': 78, 'Li': 85}

This is the most common real-world use: turning parallel lists, such as CSV headers and a row of values, into a dictionary. The same trick inverts a dictionary: dict(zip(d.values(), d.keys())) turned {"x": 1, "y": 2} into {1: 'x', 2: 'y'} in our run. Duplicate values would collapse into one key, so check first. More dictionary patterns are in our Python dictionary guide.

What happens with uneven lengths

This is the behaviour that causes real bugs. By default, zip stops as soon as the shortest input runs out:

print(list(zip(names, [1, 2])))
[('Asha', 1), ('Ravi', 2)]

“Li” vanished without any error. If those lists came from two API calls or two columns of a file, a missing row would quietly drop data from your report.

strict=True: fail loudly on mismatches

Python 3.10 added a strict flag, described in PEP 618, for exactly this problem:

list(zip(names, [1, 2], strict=True))
ValueError: zip() argument 2 is shorter than argument 1

Tip: use strict=True whenever the lists are supposed to be the same length. A crash during testing is far cheaper than a silently short report in production.

zip_longest: keep every item

When lists may legitimately differ and you want everything, use itertools.zip_longest with a fill value:

from itertools import zip_longest
print(list(zip_longest(names, [1, 2], fillvalue=0)))
[('Asha', 1), ('Ravi', 2), ('Li', 0)]

Without fillvalue the gaps are None. Our Python itertools guide covers its siblings.

Tool Uneven inputs Use when
zip(a, b) Stops at shortest, silently Truncation is intended
zip(a, b, strict=True) Raises ValueError Lengths must match
zip_longest(a, b) Pads with a fill value Every item must appear

Unzip with the * operator

There is no unzip() function, because zip() does both jobs. Unpack a list of pairs with * and zip them again:

pairs = [("Asha", 91), ("Ravi", 78), ("Li", 85)]
names, scores = zip(*pairs)
print(names, scores)
('Asha', 'Ravi', 'Li') (91, 78, 85)

zip(*pairs) passes each pair as a separate argument, so zip collects all first items together and all second items together. Note that the results are tuples; wrap them in list() if you need to modify them.

Transpose rows and columns

m = [[1, 2, 3], [4, 5, 6]]
print([list(r) for r in zip(*m)])
[[1, 4], [2, 5], [3, 6]]

The same unpacking trick turns rows into columns. It is handy for small tables, such as turning CSV rows into per-column lists. For large numeric data, NumPy is far faster.

Compare each item with the next

Zipping a list with itself, shifted by one, gives neighbouring pairs:

data = [3, 5, 9, 14]
print([b - a for a, b in zip(data, data[1:])])     # [2, 4, 5]

from itertools import pairwise
print(list(pairwise(data)))     # [(3, 5), (5, 9), (9, 14)]

This calculates day-over-day changes, gaps between timestamps or step sizes. On Python 3.10 and later, itertools.pairwise does the same without copying the list.

Split into fixed-size chunks

print(list(zip(*[iter(range(7))] * 3)))
[(0, 1, 2), (3, 4, 5)]

This classic idiom passes the same iterator three times, so each tuple takes the next three items. But notice the trap: item 6 disappeared because the last chunk was incomplete. Use itertools.batched (Python 3.12+) or zip_longest when every item matters.

zip() is a one-shot iterator

z = zip(names, scores)
print(type(z).__name__, list(z), list(z))
zip [('Asha', 91), ('Ravi', 78), ('Li', 85)] []

The second list(z) was empty because the iterator was already used up. This laziness is why zip works on huge files and generators without extra memory, but it also means you cannot loop over the same zip object twice. Store list(zip(...)) if you need it again.

Is zip faster than indexing?

We looped over two 1,000-item lists 2,000 times, best of five runs:

Loop style Time
for x, y in zip(a, b) 0.047 s
for i in range(len(a)): x = a[i]; y = b[i] 0.065 s

zip took about 28% less time and reads more clearly. The difference is small in absolute terms, so choose zip for readability; the speed is a bonus.

Three real-world uses

Turn a CSV row into a record

header = "name,dept,salary".split(",")
row = "Asha,QA,90000".split(",")
print(dict(zip(header, row, strict=True)))
{'name': 'Asha', 'dept': 'QA', 'salary': '90000'}

Pairing a header with each row is exactly what csv.DictReader does for you, but the zip version is useful for one-off strings, log lines and API responses that arrive as parallel arrays. Adding strict=True catches a row with a missing or extra column immediately, instead of producing a record with a shifted value. Note that every value is still text; convert numbers yourself.

Find what changed between two versions

old = {"price": 10, "stock": 5, "name": "Pen"}
new = {"price": 12, "stock": 5, "name": "Pen"}
print([(k, a, b) for k, a, b in zip(old, old.values(), new.values()) if a != b])
[('price', 10, 12)]

This works because both dictionaries were built with the same key order. If the order could differ, compare by key instead: [(k, old[k], new[k]) for k in old if old[k] != new.get(k)]. Assuming matching order is a classic zip bug, so be explicit about it.

Check test inputs against expected outputs

inputs = [2, 5, 0]
expected = [4, 25, 0]
print(all(x * x == e for x, e in zip(inputs, expected, strict=True)))   # True

Parallel lists of inputs and expected results are common in quick checks and data-driven tests. In a real test suite, prefer one list of pairs, which cannot drift out of step, or pytest parametrize.

zip vs enumerate vs itertools.product

These three are often confused. zip pairs items by position across several sequences. enumerate pairs each item with a counter. itertools.product pairs every item with every other, like nested loops: product("ab", [1, 2]) gave ('a', 1), ('a', 2), ('b', 1), ('b', 2), four results where zip would give two. Choose by the question you are asking: “which items belong together?” is zip, “where is this item?” is enumerate, and “all combinations?” is product.

Common mistakes

  • Silent truncation: lists of different lengths lose data. Add strict=True.
  • Reusing a zip object: it is empty the second time.
  • Zipping sets or unordered data: sets have no guaranteed order, so pairs can be mismatched. Sort first; see our Python sort list guide.
  • Expecting lists back from unzip: zip(*pairs) returns tuples.
  • Forgetting the incomplete last chunk with the [iter(x)] * n idiom.

Python zip cheat sheet

Goal Code
Loop two lists for a, b in zip(x, y)
Lists to dict dict(zip(keys, values))
Require equal length zip(x, y, strict=True)
Keep all items zip_longest(x, y, fillvalue=0)
Unzip pairs a, b = zip(*pairs)
Transpose list(zip(*matrix))
Neighbour pairs zip(x, x[1:]) or pairwise(x)
With a counter enumerate(zip(x, y))

Final thoughts

Python zip() is one of the simplest ways to make loops clearer: it pairs related data by position and removes index bookkeeping. Remember its one dangerous default, stopping at the shortest input, and guard against it with strict=True or zip_longest. Add zip(*...) for unzipping and transposing, and you have covered nearly every real use. For building new lists from zipped data, our list comprehension guide is the natural next step.

Frequently asked questions

What does zip() do in Python?

It takes two or more iterables and returns an iterator of tuples, where each tuple holds the items at the same position from every input.

What happens if lists have different lengths in zip?

zip stops at the shortest input and silently drops the extra items. Use strict=True to raise an error instead, or itertools.zip_longest to keep every item with a fill value.

How do you unzip a list of tuples in Python?

Use zip with the unpacking operator: a, b = zip(*pairs). It returns tuples, so wrap them in list() if you need lists.

How do I make a dictionary from two lists?

Call dict(zip(keys, values)). Add strict=True on Python 3.10 or later if the two lists must have the same length.

Why is my zip object empty the second time?

zip returns a one-time iterator. Once you loop over it or call list() on it, it is used up. Save the result as a list if you need it again.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
Software Development

HTTP Methods Explained: GET, POST, PUT, PATCH, DELETE, Tested on a Live Server

HTTP methods explained with a small server we ran: GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS, safe vs idempotent,…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Databases & SQL

SQL ORDER BY Multiple Columns: ASC, DESC, NULLS LAST, Case and Custom Order

SQL ORDER BY with multiple columns explained with tested queries: mixed ASC and DESC, tie-breakers, NULLS FIRST and LAST, case-insensitive…

Read article →
Databases & SQL

SQL Running Total: SUM OVER, Per-Group Totals, Moving Sums and the RANGE Trap

How to calculate a SQL running total with SUM() OVER: per-group totals, daily cumulative sums, moving sums, percent of total,…

Read article →
Software Development

JavaScript Sort Array: Numbers, Objects, Strings and Why 10 Comes Before 5

How to sort an array in JavaScript correctly: numbers with a compare function, objects by one or more fields, strings…

Read article →
Software Development

Python String Methods: Cheat Sheet, Real Examples and the strip() Trap

Python string methods with tested examples: split, join, strip, replace, find, startswith, is-methods, casefold, partition and translate, plus the strip()…

Read article →
Software Development

Python zip() Explained: Loop Two Lists at Once, Unzip, strict=True and Traps

Python zip() pairs items from several lists in one loop. Tested examples for dicts, unzipping with *, strict=True, zip_longest, sliding…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
Software Development

UTF-8 Encoding Explained: How Text Becomes Bytes and How to Fix Garbled Text

UTF-8 encoding explained with byte-level examples we ran in Python: how characters become 1 to 4 bytes, why café turns…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Databases & SQL

Delete Duplicate Rows in SQL: 5 Safe Methods, Tested Step by Step

How to delete duplicate rows in SQL safely: find them, preview them, then remove them with ROW_NUMBER, MIN(id), EXISTS, rowid…

Read article →
Databases & SQL

SQL RANK vs DENSE_RANK vs ROW_NUMBER: Differences with Tested Examples

SQL RANK vs DENSE_RANK vs ROW_NUMBER in one table: how each handles ties, top-N per group, the second-highest salary trap…

Read article →
Software Development

JavaScript Optional Chaining (?.) Explained: 8 Examples, ?? Defaults and Traps

JavaScript optional chaining stops “Cannot read properties of undefined” errors. 8 tested examples for properties, arrays and methods, ?? vs…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Software Testing

Pairwise Testing Explained: How All-Pairs Cuts 216 Tests to 13, Tested

Pairwise testing explained with a generator we ran in Python 3.13: a checkout with 216 combinations covered by 13 tests,…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →
Databases & SQL

SQL COALESCE Explained: Defaults, NULLIF, IFNULL vs ISNULL and Traps, Tested

SQL COALESCE explained with queries we ran in SQLite 3.50: first non-null values, empty strings, NULL in maths, NULLIF for…

Read article →
Databases & SQL

SQL Self Join Explained: Employee-Manager, Pairs and Row Comparisons, Tested

SQL self join explained with queries we ran in SQLite 3.50: employee and manager, earning more than the manager, unique…

Read article →
Artificial Intelligence

LLM Context Window Explained: Tokens, Limits and How to Fit More, Measured

The LLM context window explained with token counts we measured using tiktoken: words vs tokens for prose, code and Hindi,…

Read article →
DevOps

Git Cherry-Pick Explained: Copy the Commit You Need, Safely, Tested

Git cherry-pick explained with commands we ran in Git 2.56: copying a hotfix to a release branch, new hashes and…

Read article →
Test Automation

Snapshot Testing Explained: How It Works, When It Helps and When It Hurts

Snapshot testing explained with a pytest and syrupy demo we ran: creating snapshots, reading the diff after a code change,…

Read article →
Software Testing

Mutation Testing Explained: Why 100% Coverage Still Missed Our Bug

Mutation testing explained with a small mutation tool we built and ran: 14 mutants, a test suite with 100% line…

Read article →
Artificial Intelligence

Prompt Injection Explained: How AI Apps Get Tricked and How to Defend Them

Prompt injection explained for builders: direct and indirect attacks, why keyword filters fail (our test blocked 1 of 4), and…

Read article →
DevOps

DNS Records Explained: A, AAAA, CNAME, MX, TXT and TTL With Real Lookups

DNS records explained with lookups we ran: how resolution works, A and AAAA, CNAME rules, MX and null MX, TXT…

Read article →
DevOps

Feature Flags Explained: Safe Releases, Gradual Rollouts and Flag Hygiene

Feature flags explained with a rollout simulation we ran: flag types, percentage rollouts with stable hashing, kill switches, allow lists,…

Read article →
Test Automation

Test Data Generation With Python Faker: Realistic, Repeatable and Safe Data

Test data generation with Python Faker, run and measured: seeding for repeatable data, locales, unique values, domain-shaped records, edge cases…

Read article →
Software Testing

Shift-Left Testing Explained: Find Bugs Earlier Without Slowing the Team

Shift-left testing explained: what it means, why early defects are cheaper, practices from requirement reviews to CI checks, the tester's…

Read article →
Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →