-2

I am using Python version 3.7.4 on Windows 10 Enterprise.

I am facing a weird issue with Python's print function and especially sep parameter.

In Python REPL, when I use code print(1, 2, 3, 4, 5, sep='\t'), I get proper output as 1 2 3 4 5

However when code tries to iterate over a collection as shown below, instead of showing number separated by a tab, it always displays individual value on a new line.

numbers = {1, 2, 3, 4, 5}
for n in numbers:
    print(n, sep='\t')

Can someone please help me to understand why its displaying number value on a separate line?

I have attached screenshot for the reference.

Python print function sep parameter

Thanks.

Prasad Honrao
  • 211
  • 3
  • 18
  • 2
    `sep` separates multiple *values* within one print, not multiple prints. – deceze Dec 08 '19 at 20:58
  • 2
    You `sep` only separates the arguments you pass to `print`, in your loop, you only ever pass a single argument. You can use the `end` parameter instead, or unpack the collection as multiple arguments up front using the splat operator: `print(*numbers, sep='\t')` – juanpa.arrivillaga Dec 08 '19 at 20:58
  • Thank you everyone for quick response. That clarifies – Prasad Honrao Dec 08 '19 at 21:04

1 Answers1

3

It is because you are iterating over the set numbers. The loop runs and the print() function automatically inserts a \n at the end of each item it prints out for display. Hence each item is being displayed on its own line.

If you wanted to loop through an iterable like in your example and have it separated by a tab, then you can do the following:

for n in numbers:
    print(n, end='\t')

By default, the end argument is set to \n.

probat
  • 1,422
  • 3
  • 17
  • 33