[Tutor] Print elements of list with newlines

Dennis Lee Bieber wlfraed at ix.netcom.com
Fri Oct 22 14:01:47 EDT 2021


On Fri, 22 Oct 2021 16:58:21 +0200, Julius Hamilton
<juliushamilton100 at gmail.com> declaimed the following:

>Hey,
>
>Is there any way to print the elements of a list one by one on new lines,
>in a brief single line of code, as opposed to:
>
>for item in list:
>  print(item)
>
	Suspect you won't like it (since you specified "single line")

	print("\n".join([str(itm) for itm in lst]))

List comprehension (hmmm, generator expression might work as well), taking
each item from the list, forcing the item into a STRING format, then join
the items with a new-line between each.

>>> lst = [	1,	3.14159,
... 	"a string",	("a", "tuple")	]
>>> print("\n".join([str(itm) for itm in lst]))
1
3.14159
a string
('a', 'tuple')
>>> 

>>> print("\n".join((str(itm) for itm in lst)))
1
3.14159
a string
('a', 'tuple')
>>> 

	Generator expression works too, and may avoid creating the intermediate
list.


-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/



More information about the Tutor mailing list