Skip to content Skip to sidebar Skip to footer

Python: Print All The String From List At The Same Time

For example, I have a list a. When I do it in a for loop, I can print all of its elements. But when I do it outside of the for loop, it only prints the last one. How can I print th

Solution 1:

You can use print with * and a separator of a newline:

print(*a, sep='\n')
print("====================")
print(*a, sep='\n')

Output:

a is apple
b is banana
c is cherry
====================
a is apple
b is banana
c is cherry

The print(*a) is equivalent to print(a[0], a[1], a[2], ...). This would print it with a white space in between. Overriding this default with sep='\n' gives you a newline instead.

If you want to reuse it, write your own, small helper function:

def myprint(a):
    print(*a, sep='\n')

myprint(a)

A one-liner alternative, but arguably less readable:

print(*(a + ["=" * 20] + a), sep='\n')

Output:

a is apple
b is banana
c is cherry
====================
a is apple
b is banana
c is cherry

In Python 2 "turn on" the Python-3-style print function with:

from __future__ import print_function

Solution 2:

You can multiply list by 2 and append separator in middle of the list and then simply print the list using join method.

l = ['a is apple','b is banana','c is cherry']
l = l*2 
#['a is apple', 'b is banana', 'c is cherry', 'a is apple', 'b is banana', 'c is cherry']
l = l.insert(int(len(l)/2), '====================')
#['a is apple', 'b is banana', 'c is cherry', '====================','a is apple', 'b is banana', 'c is cherry']
print('\n'.join(l))

This will output:

a is apple
b is banana
c is cherry
====================
a is apple 
b is banana
c is cherry

Solution 3:

You can use join() and pass list to it as follows:

a=['a is apple','b is banana','c is cherry']
print("\n".join(a))
print("====================")
print("\n".join(a))

output

a is apple
b is banana
c is cherry
====================
a is apple
b is banana
c is cherry

Solution 4:

Try this one. This will give what you need

x,y,z=a
print(x,y,z)

Solution 5:

This is the simplest and cleanest way of doing it (universal across Python 2 and 3):

print('\n'.join(a + ["===================="] + a))

This is the Python-3-only version:

print(*(a + ["===================="] + a), sep='\n')

Post a Comment for "Python: Print All The String From List At The Same Time"