Ad

How To Append Two Lists In Order Into A Text File?

- 1 answer

Say I have two lists:

a = [1, 2, 3, 4]

b = [hello, how, iz, life]

How can I make a new list c that takes each element in list a and matches it in order to an element in list b? I want the text file to look something like this:

1 hello
2 how
3 iz
4 life

I attempted c.append(a,b), but I got the following error:

TypeError: list.append() takes exactly one argument (2 given)
Ad

Answer

Try the following:

a = [1, 2, 3, 4]

b = ["hello", "how", "iz", "life"]


c = zip(a,b)

with open("sample.txt", 'w') as outfile:
    for elem in c:
        outfile.write(str(elem[0]) + " " + elem[1] +"\n")

This will output:

1 hello
2 how
3 iz
4 life

to a file called sample.txt.

Edit: Kelly makes a great point you can just simplify the line as print(*elem, file=outfile). I looked at the docs for print and I was surprised to find that the print function defines a separator for elements given in the *objects argument and ends the line with a newline through default arguments, which provides us with the same desired output.

Ad
source: stackoverflow.com
Ad