ERJAN
ERJAN

Reputation: 24500

How to use one print() in python to print list items line by line - not in one streak?

mister is a list of lists. print(mister) gives this in the Python shell:

[['ququ.kz', 1], ['gp.kz', 1], ['gmail.ru', 1], ['mail.ru', 1], ['tlc.com', 1], ['mail.ko', 1], ['microsoft.jp', 1], ['hotmail.eu', 1], ['soman.com', 1], ['swedenborgen.sn', 1], ['customergoogle.com', 1], ['mail.jp', 2], ['gmail.com', 3], ['mail.ru', 3], ['hotmail.com', 3], ['mail.jp', 3], ['mail.com', 4], ['hotmail.com', 4], ['gmail.com', 4], ['mail.kz', 5], ['mail.cn', 7], ['hotmail.com', 9], ['customers.kz', 9], ['microsoft.com', 10], ['conestogamall.com', 13]]

Can I use print() one time and get nice output - line by line, instead of one big streak? Or is the only solution:

for email_date_entry in mister:
    print(email_date_entry)

Is there another elegant way to use only one print call?

Upvotes: 0

Views: 109

Answers (3)

Aylen
Aylen

Reputation: 3554

Edit based on @jonrsharpe's suggestion

Try this:

print('\n'.join(map(str, mister)))

What this code does:

  • Converts to string every item in the list.
  • Joins all obtained strings by a line break separator.
  • Prints the result.

This approach works for both Python2.x and Python3.x.

Upvotes: 2

Jan Spurny
Jan Spurny

Reputation: 5528

You can also use pprint (Pretty Print) from pprint module - it works for almost every type and usually gives nice output. Usage:

from pprint import pprint
...
pprint(mister)

Upvotes: 3

Martijn Pieters
Martijn Pieters

Reputation: 1121524

You can pass your list as separate arguments to print() using the * variable argument syntax:

print(*mister, sep='\n')

Now each element in mister is seen as a separate argument, and is printed with a \n separator:

>>> mister = [['ququ.kz', 1], ['gp.kz', 1], ['gmail.ru', 1], ['mail.ru', 1], ['tlc.com', 1], ['mail.ko', 1], ['microsoft.jp', 1], ['hotmail.eu', 1], ['soman.com', 1], ['swedenborgen.sn', 1], ['customergoogle.com', 1], ['mail.jp', 2], ['gmail.com', 3], ['mail.ru', 3], ['hotmail.com', 3], ['mail.jp', 3], ['mail.com', 4], ['hotmail.com', 4], ['gmail.com', 4], ['mail.kz', 5], ['mail.cn', 7], ['hotmail.com', 9], ['customers.kz', 9], ['microsoft.com', 10], ['conestogamall.com', 13]]
>>> print(*mister, sep='\n')
['ququ.kz', 1]
['gp.kz', 1]
['gmail.ru', 1]
['mail.ru', 1]
['tlc.com', 1]
['mail.ko', 1]
['microsoft.jp', 1]
['hotmail.eu', 1]
['soman.com', 1]
['swedenborgen.sn', 1]
['customergoogle.com', 1]
['mail.jp', 2]
['gmail.com', 3]
['mail.ru', 3]
['hotmail.com', 3]
['mail.jp', 3]
['mail.com', 4]
['hotmail.com', 4]
['gmail.com', 4]
['mail.kz', 5]
['mail.cn', 7]
['hotmail.com', 9]
['customers.kz', 9]
['microsoft.com', 10]
['conestogamall.com', 13]

Upvotes: 5

Related Questions