PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, May 12, 2022

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

 May 12, 2022     append, python     No comments   

Issue

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)

Solution

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.



Answered By - Richard K Yu
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing