The open blogging platform. Say no to algorithms and paywalls.

3 Ways to Print List Elements on Separate Lines in Python

A guide on printing Python list elements on new lines

image

Image by Author

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.

image

Figure 1: Using the standalone print function to print list elements.

  1. 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
    
  2. 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
    
  3. Use the print function with the join() method. The join() 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!




Continue Learning