3

I have 2 lists each of equal size and am interested to combine these two lists and write it into a file.

alist=[1,2,3,5] 
blist=[2,3,4,5] 

--the resulting list should be like [(1,2), (2,3), (3,4), (5,5)]

After that i want that to be written it to a file. How can i accomplish this?

Chaitanya
  • 1,698
  • 5
  • 21
  • 41
  • 1
    Remove that comma at the end of your first statement. Currently `alist` is a tuple, with value `([1, 2, 3, 5],)`. – Stephan202 Nov 04 '09 at 10:49
  • 1
    Duplicate: http://stackoverflow.com/questions/803526/merge-two-lists-of-lists-python. Smells like homework. Certainly an FAQ. – S.Lott Nov 04 '09 at 11:26

2 Answers2

13
# combine the lists
zipped = zip(alist, blist)

# write to a file (in append mode)
file = open("filename", 'a') 
for item in zipped:
    file.write("%d, %d\n" % item) 
file.close()

The resulting output in the file will be:

 1,2
 2,3
 3,4
 5,5
Ben James
  • 121,135
  • 26
  • 193
  • 155
6

For the sake of completeness, I'll add to Ben's solution that itertools.izip is preferable especially for larger lists if the result is used iteratively, as the final result is not an actual list but a generator:

from itertools import izip
zipped = izip(alist, blist)
with open("output.txt", "wt") as f:
    for item in zipped:
        f.write("{0},{1}\n".format(*item))

The documentation for izip can be found here.

Community
  • 1
  • 1
RedGlyph
  • 11,309
  • 6
  • 37
  • 49
  • 2
    Good point; this is worth doing if you are using 2.6 or earlier. In Python 3, `zip()` produces an iterator rather than a list – Ben James Nov 04 '09 at 11:11
  • @Ben: Yes, you are right! I didn't mention that for Python 3 but it's worth knowing. – RedGlyph Nov 04 '09 at 11:33