Home > front end >  Extended unpacking not creating separate items in list
Extended unpacking not creating separate items in list

Time:12-22

I am executing the below code:

s = 'python'
a, b, *c, d = s[0], s[1], s[2:-1], s[-1]
print(c)

I am getting output as ['tho']

Please help me understand why the output is not ['t', 'h', 'o'] ?

As we are using the * operator on LHS, so the output should be ['t', 'h', 'o'] and not ['tho']

CodePudding user response:

It's because s[2:-1] is not unpacked. There is no reason for it to unpack.

You need:

a, b, *c, d = s[0], s[1], *s[2:-1], s[-1]

Unpack assignments will only unpack into one sequence of multiple values when there are multiple non-attached values, like 't', 'h', 'o', not when the value is 'tho'.


Now:

print(c)

Is:

['t', 'h', 'o']

CodePudding user response:

You would need to unpack the string as well, else there is only a single element ('tho'):

s = 'python'
a, b, *c, d = s[0], s[1], *s[2:-1], s[-1]
print(c)

Output: ['t', 'h', 'o']

I this what you were looking for is:

a,b,*c,d = s
print(c)

where unpacking really makes sense

  • Related