Why print unpacked list of number return a sequence of number in the same line

I tested the code below but didn’t understand why it didn’t print number line by line.

Input:

lst = [1, 2, 3, 4]
print(*lst)

Output:

1 2 3 4

Expected:

1
2
3
4

Is there any expert can explain the details behind that behavior? Thanks in advance.

print(*lst) is effectively print(1, 2, 3, 4) in this case. The only newline is added by the print statement at the end, not between every argument.

2 Likes

Not too sure why you expected what you expected.

The * is an iteration as in print(*'Hello')

Maybe a better example is if say you want to 4 empty lines:
print(4*'\n')
{edit: this is more of a ‘use case’ rather than an example of ‘unpacking’. Sorry if it caused any confusion}

To get the output you expected, you’d need something like this:
for element in lst: print(element)

Did you notice that earlier today I send you a solution to get the result which you expected here?

I suggest you checking the documentation:

Focus on the arguments sep and end.

As Skip says print(*lst) is equivalent to doing print(1, 2, 3, 4) so all the output is on the same line, seperated by spaces.

If you want the output on separate lines you can either call print for each item separately:

for item in lst:
    print(item)

or tell print to use a newline as the seperator:

print(*lst, sep='\n')

Huang, I see you used ' * ' here and in your other topic and you got unexpected results both times. ' * ' is used to feed the members of a group data object one by one instead of as a single group object. It is normally used inside of a def(): function block to feed argument values to the function. Python is amazingly flexible and is happy to let you use it in a print() function. However, you should probably not use ' * ' before learning more basic Python and FULLY understand WHEN to use ' * '.

Rob came close to explaining but maybe his answer was lost in the other detail.

“Iterate” means ‘to repeat an action’. In Python the action is ‘feed group members one at a time’.   * is an iterator instruction.

Did you run Rob’s print(*'Hello') example?

1 Like

I got it. Thanks for your helps. Now I can understand more about unpack.