Open In App

Print a List in Horizontally in Python

Last Updated : 18 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Printing a list horizontally means displaying the elements of a list in a single line instead of each element being on a new line. In this article, we will explore some methods to print a list horizontally in Python.

Using * (Unpacking Operator)

unpacking operator (*) allows us to print list elements directly separated by a space.

Python
a = [1, 2, 3, 4, 5]

# Using unpacking to print horizontally
print(*a)

Output
1 2 3 4 5

Explanation:

  • The * operator unpacks the list elements and passes them as arguments to the print() function.
  • Works for lists with mixed data types without additional conversions.

Let's see some more methods to print a list horizontally in Python

Using join() Method

join() method is also one of most simplest and efficient ways to print a list horizontally.

Python
a = ['Geeks', 'for', 'Geeks']

# Joining list elements with a space
print(' '.join(a))

Output
Geeks for Geeks

Explanation:

  • join() method concatenates list elements with the specified delimiter (a space here).
  • If the list contains other types, convert them to strings first.

Using List Comprehension

List comprehension can be combined with unpacking or string conversion to print elements in one line.

Python
a = [1, 'two', 3.0, 'four']

# List comprehension with unpacking
print(' '.join([str(x) for x in a]))

Output
1 two 3.0 four

Explanation:

  • Converts all elements to strings before using join().
  • Ideal for lists with mixed data types that need horizontal formatting.

Using a Loop

A for loop is a flexible way to print elements horizontally, especially if custom formatting is required.

Python
a = [3.14, 2.71, 1.41]

# Loop to print elements in one line
for x in a:
    print(x, end=' ')

Output
3.14 2.71 1.41 

Explanation:

  • The end=' ' parameter in print() avoids adding a newline after each element.
  • Useful for more complex or conditional formatting.

Practice Tags :

Similar Reads