what's the difference between
for i in list:
print(*i,sep="")
And this print statement
for i in list:
print(i)
what's the difference between
for i in list:
print(*i,sep="")
And this print statement
for i in list:
print(i)
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).
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