Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to append two lists in order into a text file?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

Try the following:

a = [1, 2, 3, 4]

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


c = zip(a,b)

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

This will output:

1 hello
2 how
3 iz
4 life

to a file called sample.txt.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading