# Print two lists side by side in Python

Learn how to print two Python lists in aligned columns using zip, ljust and f-strings, handle uneven lengths, and mark the rows that differ.

To print [two lists side by side](/articles/compare-two-lists-side-by-side/) in Python, loop over zip and print each pair. For neat columns, pad the left item to a fixed width with ljust or an f-string. Switch to itertools.zip_longest when the lists differ in length, so no row gets dropped. 

- The zip function pairs items by position, giving one row per pair of items.
- Plain zip stops at the shorter list, so extra items vanish without warning.
- Pad the first column with ljust or a format spec like :<20 for alignment.
- Measure the longest string in the first list to set the column width automatically.
- Compare each pair inside the loop to flag the rows whose values differ.
 

## How zip pairs two lists row by row 

The zip function in Python pairs items from two lists by their position. Calling zip(names, prices) yields tuples like ('apple', 3), one tuple for each index. A for loop can unpack each tuple into two variables, such as for a, b in zip(x, y). Printing a and b on the same line gives the side-by-side view. 

The simplest output comes from print(a, b), which separates the two values with one space. Short, even items look fine this way, but uneven lengths make the second column wander. A tab separator, passed as sep='\t', lines things up only when items stay shorter than a tab stop. 

Python print formatting starts to matter once the output is meant for a person to read. Fixed-width text output means each column occupies the same number of characters on every line. Padding achieves that by adding spaces after shorter strings until they reach the chosen width. 

## Aligning text columns with ljust and rjust 

The str.ljust method pads a string with spaces on the right until it reaches a given width. Writing print(a.ljust(15), b) starts the second column at the same position on every line. Strings already longer than the width come back unchanged, so they push that row out of line. 

Values that are not strings need converting first, because ljust exists only on str objects. Wrapping each item with str() handles numbers, dates and None without raising an AttributeError. The sibling methods rjust and center align text to the right or the middle instead. 

Right alignment suits numeric columns, since digits then line up by their last place. Calling str(price).rjust(10) in the second column keeps prices tidy and easy to compare. A custom fill character also works, as in a.ljust(20, '.'), which draws a dotted leader. 

## Using f-string format specs for alignment 

An f-string format specification aligns columns without calling ljust on every item. The expression f'{a:<15}{b}' left-aligns a in a field fifteen characters wide. The symbols <, > and ^ mean left, right and center alignment within that field. 

Format specs also convert values on the fly, so numbers need no separate str() call. A spec like {price:>10.2f} right-aligns a float and shows exactly two decimal places. Width can come from a variable too, written as f'{a:<{w}}' with w set earlier. 

The older str.format method accepts the same mini-language, as in '{:<15}{}'.format(a, b). Code that must run on very old interpreters can rely on it, while newer code reads better with f-strings. Both approaches produce identical output, so the choice comes down to readability. 
| Approach | Example | Fits | 
| Plain print | print(a, b) | Quick checks with short items | 
| Tab separator | print(a, b, sep='\t') | Items shorter than one tab stop | 
| str.ljust | print(a.ljust(15), b) | Simple left-aligned text columns | 
| f-string spec | print(f'{a:<15}{b:>10}') | Mixed text and numbers | 
| Table library | tabulate(rows) | Headers, borders and many columns |  

## Handling lists of different lengths 

The zip function stops at the end of the shorter list and ignores leftover items. No error appears, so a missing row can easily go unnoticed in the output. Comparing listings this way can hide the very entries that one source has and the other lacks. 

The itertools.zip_longest function keeps going until the longer list runs out. Missing positions get the value None, or any placeholder passed as fillvalue='-'. A dash or an empty string reads more clearly than None in a printed column. 

Newer Python releases accept zip(a, b, strict=True), which raises a ValueError when the lengths differ. That check suits cases where both lists must match exactly, such as paired fields. Printing len(a) and len(b) before the loop gives a quick manual check on older versions. 

## Setting column width from the longest item 

A column width calculated from the data keeps every row aligned without guessing a number. The expression max(len(str(x)) for x in names) returns the length of the longest entry. Adding two or three spaces to that value leaves a clear gap before the next column. 

Header text belongs in the width calculation too, or a long title will break the alignment. A simple way is to measure the headers and the items together in one max call. The resulting width then feeds ljust or a nested f-string spec such as {a:<{w}}. 

Very long items can make the first column too wide for the screen. Truncating with a slice like a[:30] keeps the layout readable at the cost of hiding characters. The textwrap module offers another route, splitting long text across several lines. Wrapped cells need extra code, though, so that each column stays in its own lane. 

## Marking the rows whose values differ 

Rows that differ between two lists stand out once each pair is compared inside the loop. A test like a != b inside the for loop can add a marker to that line. A short symbol such as an asterisk or the word DIFF in a third column works well. 

Comparison results depend on how the values are stored, not on how they look printed. The string '3' and the integer 3 print the same but are not equal in Python. Normalizing both sides first, with str(), strip() or lower(), avoids false differences from type, spaces or case. 

Terminal color makes differing rows easier to spot in long output. ANSI escape codes, special character sequences that terminals read as color commands, can wrap a line in red. Some terminals and log files show those codes as raw characters, so a text marker remains the more portable option. 

- Pair the lists with zip_longest so no item is skipped
- Normalize each value with str() and strip()
- Compare the two values in each pair
- Print a marker column when the values do not match
- Count the flagged rows to see how many differ
 

## When a table library makes more sense 

A table library such as tabulate or rich handles column alignment, headers and borders automatically. Both are third-party packages installed with pip, so they add a dependency to the project. Passing list(zip(a, b)) and a headers argument to tabulate prints a ready-made grid. 

The pandas library suits larger comparisons, where two lists become columns of a DataFrame. A DataFrame, a labeled two-dimensional table, prints with aligned columns by default. Boolean filters like df[df.a != df.b] then show only the rows that differ. 

Plain print with ljust or f-strings remains enough for scripts, quick checks and small listings. Avoiding extra packages keeps a script easy to share with other Python users. Readers who open the output in a spreadsheet may prefer a CSV file written with the csv module. 

## Questions about printing lists side by side 

### Why does zip skip items from my longer list? 

Plain zip stops at the end of the shorter list by design. Swap in itertools.zip_longest with a fillvalue to keep every item from the longer list. Passing strict=True in newer Python releases raises an error instead of skipping items. 

### How do I align numbers to the right in the second column? 

Right alignment comes from a format spec such as f'{b:>10}' or from str(b).rjust(10). For floats, f'{b:>10.2f}' also fixes the display at two decimal places. Numbers aligned this way line up by their last digit, which makes them easier to compare. 

### Can I print more than two lists side by side? 

Yes, zip accepts any number of lists and returns one tuple per position. A loop like for a, b, c in zip(x, y, z) prints three columns. Each column except the last needs its own width in the format spec. 

### Why are my columns still misaligned after using ljust? 

Misaligned columns after ljust come from an item longer than the chosen width or from tab characters. Calculating the width from the longest item fixes the first cause. Emoji and East Asian characters can fill two terminal cells, while len() counts each one once. The third-party wcwidth package measures display width for those cases. 

### How do I add headers above the two columns? 

Headers print with the same format spec as the data rows, placed before the loop. A line such as '-' * total_width underneath separates the titles from the values. Including header lengths in the width calculation keeps titles and data aligned. 

### Does print add a space between the two columns? 

Yes, print separates its arguments with a single space by default. Passing sep='' removes that space, while sep=' | ' draws a visible divider between columns. A divider helps when values contain spaces of their own.
