I often want to print the elements of a list. Unfortunately, the print function packs the list elements and often makes the output unreadable(e.g., Figure 1). Below are three ways to print list elements so that each element appears on a new line.
-
For a beginner, the easiest way is to use a for loop to print each list element. However, this method is my least favorite.
for result in results: print (result) # Element number: 1, Result: 212 # Element number: 2, Result: 134 # Element number: 3, Result: 151 # Element number: 4, Result: 104 # Element number: 5, Result: 174
-
Use a starred expression to unpack the list. In the print function below, the asterisk
*
denotes iterable unpacking. You can read more about Expression lists in Python Documentation.print(*results,sep='\n') # Element number: 1, Result: 212 # Element number: 2, Result: 134 # Element number: 3, Result: 151 # Element number: 4, Result: 104 # Element number: 5, Result: 174
-
Use the print function with the
join()
method. Thejoin()
method takes all items in the list and joins them into a single string.print("\n".join(results)) # Element number: 1, Result: 212 # Element number: 2, Result: 134 # Element number: 3, Result: 151 # Element number: 4, Result: 104 # Element number: 5, Result: 174
I hope you found these code snippets helpful. Thank you for reading!