Smith Lo
Smith Lo

Reputation: 315

why print(*iterable_list) return as string?

when I print iterable list, it will return as list but if I use * then it will print as a string rather than list.

numbers = [1, 3, 5, 7, 13]
print(numbers)
#[1, 3, 5, 7, 13]

print(*numbers)
#1 3 5 7 13

normally if I use * to unpack something, it will return as list:

a, *b = numbers
print(b)
#[3, 5, 7, 13]

but why use * in print return as string? I believe I might misunderstand something or maybe I just not clearly understand something here

could anyone point me out:

  1. why print(*iterable_list) return as string?

  2. what is the use cases of print(*iterable_list)?

Thank you

Upvotes: 1

Views: 70

Answers (2)

Ankit Agrawal
Ankit Agrawal

Reputation: 611

As you just said that * is used to unpack something. Then from this, I think that it is again unpacking the list or something else with * and keeping in print this * means keeping it with comma separated variables and by default python print have sep by space so it is returning a string with space separated values. I am not sure about this...but i thought that it should work

Upvotes: 0

DYZ
DYZ

Reputation: 57105

First things first, function print always returns None and never numbers or strings.

The asterisk operator converts its right operand (an iterable) to an argument list. print(*numbers) is equivalent to print(numbers[0],numbers[1],numbers[2],...). Each of the items is printed separately - in your case, as a number.

Conversely, print(numbers) prints numbers as a list, with all the list formatting, such as commas and square brackets.

As for the use cases, I think your example is a clear illustration of the difference.

Upvotes: 1

Related Questions