Zaibi Zaibi - 1 year ago 24
Python Question

How to combine two list in to one with two columns

Two lists

x = ['a','b','c','d','e']
y = ['s','t','u','v','w','x','y','z']

How do I combine these two results and dump these to a CSV file with two columns, I have tried using
but it removes some end objects of list
. Most of the solution provides for those cases where objects in
are equal, as you can see in my case that is not.


Use the itertools.izip_longest() function instead, and tell it what to use for those missing columns; for a CSV file an empty string would work:

for row in izip_longest(x, y, fillvalue=''):
    # ...

Note that in Python 3, the i prefix was dropped from the function name.

If you are writing these to a CSV file, you can send the whole object to the csv.writer.writerows() function directly:

import csv
from itertools import izip_longest

with open(filename, 'wb') as outf:
    writer = csv.writer(outf)
    writer.writerows(izip_longest(x, y, fillvalue=''))