Print values in a List without Spaces in Python

In this article, we will discuss different ways to print the values in a list without spaces in Python.

Table Of Contents

The string class in Python, provides a method join(). It accepts a sequence of strings as an argument, and joins all the strings in the sequence to make a single string. We can use, this to convert list elements to a string by using an empty string as delimeter, and then print that big string. But we need to make sure that list has only string elements. If list has some other type of elements then we need to convert them to string first. Let’s use this join() method.

If your list contains only strings, then you can directly pass the list to the join() function of an empty string object. It will join all the strings in list to single string without spaces, because we are using an empty string as delimeter. Then we can print that string. Let’s see an example,

listOfStrs = ['This', 'is', 'a', 'sample', 'text']

# join all the strings in list without spaces
strValue = ''.join(listOfStrs)

print(strValue)

Output:

Thisisasampletext

In this case, we will handle a list which has some integers. For this, first we will convert all the elements of lists to string using list comprehension and str() function. Then pass that list to join() function of an empty string object. It will give us a joined string without spaces, then we will print that string. Let’s see an example,

listOfNumbers = [2022, 12, 23]

# create a string by joining all integers in list 
strValue = ''.join([str(elem) for elem in listOfNumbers])

print(strValue)

Output:

20221223

Convert all the elements of lists to string using map() and str() functions. The map() function will apply str() function on all list elements to convert them to string. Then pass those elements to join() function of an empty string object. It will give us a joined string without spaces, then we will print that string. Let’s see an example,

listOfNumbers = [2022, 12, 23]

# create a string by joining all integers in list 
strValue = ''.join(map(str, listOfNumbers))

print(strValue)

Output:

20221223

Pass an empty string as sep argument to the print() function along with the list. It will print all list elements without spaces. Let’s see some examples,

Example 1:

listOfStrs = ['This', 'is', 'a', 'sample', 'text']

# print list elements without spaces
print(*listOfStrs, sep='') 

Output:

Thisisasampletext

Example 2:

listOfNumbers = [2022, 12, 23]

# print list elements without spaces
print(*listOfNumbers, sep='')

Output:

20221223

Summary

We learned about different ways to print list values without spaces in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top