Search code examples
pythonstringlistprintingsplice

How to print items from a list on new lines efficiently?


So I've got the following example code:

def example(x):
    list = [1,2,3]
    if(insert_thing):
      print(1,2,3 on new lines)

What I want to do is if a certain condition happens, the contents of my list will be printed on new lines. So the output of this would be: 1 2 3

I'm looking to do this for multiple if statements (using multiple lists depending on the if statement; i.e

list1 = [0,1,2] list2= [4,6,7]
if(condition):
   print(list1[0])
   print(list1[1])
   print(list1[2])
elif(condition):
   print(list2[0])....

and so on. How would I go about streamlining this printing of the contents on new lines into less lines? Should I make a new function (and if so, what sort of approach should I be using?)?

I'm wracking my brain to figure out a solution and am well and truly stumped; hence why I've turned to asking some other people what they might think. Thanks for any help!


Solution

  • If efficiency is what you wanted, you can do this by joining the list with a newline separating every item:

    list1 = [0,1,2] 
    list2= [4,6,7]
    if(condition):
       print("\n".join(list(map(str,list1))))
    

    Or do this which using a the print functions in Python3:

    print(*list1, sep="\n")