简体   繁体   中英

Unpacking list and assigning it to variable

For this code,

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

I would get output as 1 2 3 4 5 as the list a gets unpacked.

But what if I want to assign *a to a variable x and then print?

a=[1,2,3,4,5]
x=*a
print(x)

How to get the same output as the above code ?

To get the same output from print , write x = ' '.join(str(s) for s in a) . However, that is not unpacking, and there is no way to use unpacking to achieve the same result here.

The unpacking operator * can only appear in the context of function arguments or an assignment target. Your original example uses unpacking for the arguments of the print function. The other way you can use unpacking is in a destructuring assignment, in which case it creates a list; for example:

>>> first, *rest = [1, 2, 3, 4, 5]
>>> first
1
>>> rest
[2, 3, 4, 5]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM