Print two presorted lists into one output file in python
Question: I have two lists that are already sorted how they need to be, and i need them
put into one file, like this example:

    
    
    list1 = [a, b, c, d, e]
    list2 = [1, 2, 3, 4, 5]
    

output file should look like:

    
    
    a1
    b2
    c3
    d4
    e5
    

im fairly new to python, so im not really all that sure how to do file
writing. I read using `with open(file, 'w') as f:` is a better/easier way to
start the writing block, but i am unsure how to merge the lists and print them
as such. I could probably merge them into a third list and print that one to
the file using `print>>f, item` but i wanted to see if there was as simpler
way.

Thank you!

Late edit: looking at my lists, they wont always be the same length, but all
the data needs printed regardless. So if list2 went to 7 then then the output
would need to be:

    
    
    a1
    b2
    c3
    d4
    e5
    6
    7
    

or vice versa, where list1 may be longer then list2.


Answer: Use the [zip()](http://docs.python.org/library/functions.html#zip) function to
combine (ie zip) your two lists. E.g.,

    
    
    list1 = ['a', 'b', 'c', 'd', 'e']
    list2 = [1, 2, 3, 4, 5]
    
    zip(list1, list2)
    

gives:

    
    
    [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
    

you can then format the output to suit your needs.

    
    
    for i,j in zip(list1, list2):
        print '%s%d' %(i,j)
    

yielding:

    
    
    a1
    b2
    c3
    d4
    e5
    

**Update** :

If your lists are unequal length, this approach using
[itertools.izip_longest()](http://docs.python.org/library/itertools.html#itertools.izip_longest)
might work for you:

    
    
    import itertools
    list1 = ['a', 'b', 'c', 'd', 'e']
    list2 = [1, 2, 3]
    
    for i,j in itertools.izip_longest(list1, list2): 
        if i: sys.stdout.write('%s' %i)
        if j: sys.stdout.write('%d' %j)
        sys.stdout.write('\n')
    

gives:

    
    
    a1
    b2
    c3
    d
    e 
    

Note, if you were using Python 3, there is a nice way to use the `print()`
function. I am using `write()` here to avoid extra blank spaces between items.

