Software Development

What is the easiest way to print a Python list or array without square brackets and commas?

KA Asked by Karen White · 14-07-2023
▲ 0 upvotes 13,361 views 0 comments
The question

I am generating a report in Python where I need to display a list of ID numbers. When I use the standard print() function, the output includes square brackets and commas, like [101, 102, 103]. I need the output to be clean, with only spaces between the numbers (e.g., 101 102 103). Is there a simple trick to unpack the list directly within the print statement, or do I have to write a loop or use the .join() method every time I want a clean display?

3 answers

▲ 0
MA
Answered on 17-07-2023

The absolute simplest "Pythonic" way to achieve this is by using the asterisk (*) operator, also known as the unpacking operator. When you use print(*my_list), Python unpacks all elements of the list and passes them as separate arguments to the print function. By default, the print function separates multiple arguments with a space, so print(*[1, 2, 3]) results in 1 2 3. If you need a different separator, like a comma without brackets, you can simply add the sep parameter, for example: print(*my_list, sep=', '). This is much more efficient than writing a manual loop and keeps your code very concise and readable for others. 

▲ 0
TH
Answered on 19-07-2023

While the unpacking operator is great for quick console logs, have you considered what happens if your list contains non-string items and you need to save the result to a variable instead of just printing it? Wouldn't using the .join() method be safer if you're building a larger string for a file or a web response?

RI 21-07-2023

Thomas, you're right to bring up the .join() method! However, a common mistake people make is trying to use ' '.join([1, 2, 3]), which throws a TypeError because join only works on strings. To fix this, you have to use a map function: ' '.join(map(str, my_list)). This converts every integer to a string first. While it's a bit more complex than the unpacking operator, it is definitely the better choice for production-level software development where you need to manipulate the string before it ever reaches the print function.

▲ 0
SU
Answered on 23-07-2023

If you prefer a more traditional approach, you can use a simple for loop with the end parameter: for x in my_list: print(x, end=' '). This gives you full control over the spacing.

KA 24-07-2023

Thanks Susan! Using the end parameter is very helpful when you're printing items one by one as they are processed in a real-time data stream.

Share your thoughts

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

Still have questions? Schedule a free counselling session

Our experts are ready to help you with any questions about courses, admissions, or career paths. Get personalized guidance from industry professionals.

Book Free Session

Book Free Session