0

what's the difference between

for i in list:
    print(*i,sep="")

And this print statement

for i in list:
    print(i)
jdehesa
  • 58,456
  • 7
  • 77
  • 121
Rebai Ahmed
  • 1,509
  • 1
  • 14
  • 21

2 Answers2

2

The print(*i,sep="") statement print all values extracted from the i iterable, without any separator.

Where print(I) will print the i value. For an iterable, it will print the string representation of each value.

See the difference:

i = [1, 2, "hi"]

print(*i, sep="")
# -> 12hi
print(i)
# -> [1, 2, 'hi']

Explanation:

The *i syntax is called "unpacking": each value of an iterable (list or tuple) is extracted and pass as-is to the arguments of the print function (which take a variable list of parameters).

Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103
  • Do you need more explanation? If not, I suggest you to upvote and [accept](https://meta.stackexchange.com/a/5235/344471) my answer. – Laurent LAPORTE Sep 04 '17 at 21:54
0

It might be easier to understand if you look at an example with a list of lists. In this case i is a list for each iteration of the loop. With a simple print statement the output will be the entire list.

The * as used in this sample, tells python to unpack the list. It's a nifty trick. The separator is optional, but can be used to insert tabs, new lines, or any other separator you want.

stuff = [['one', 'two', 'three'], ['four', 'five', 'six']]


for i in stuff:
    print(i)


for i in stuff:
    print(*i)

Output:

['one', 'two', 'three']
['four', 'five', 'six']
one two three
four five six
Chris
  • 15,819
  • 3
  • 24
  • 37