How can I unpack sequence?
Asked Answered
C

3

7

Why can't I do this:

d = [x for x in range(7)] 
a, b, c, d, e, f, g = *d

Where is it possible to unpack? Only between parentheses of a function?

Cadmarr answered 2/5, 2018 at 9:22 Comment(0)
B
4

You're using Extended Iterable Unpacking in wrong way.

d = [x for x in range(7)]  
a, b, c, d, e, f, g = d
print(a, b, c, d, e, f, g)

Where it's possible to unpack? Only between parentheses of a function?

No,

* proposes a change to iterable unpacking syntax, allowing to specify a "catch-all" name which will be assigned a list of all items not assigned to a "regular" name.

You can try something like this:

a, *params = d
print(params)

Output

[1, 2, 3, 4, 5, 6]

Usually * (Extended Iterable Unpacking) operator is used when you need to pass parameters to a function.

Note

Javascript equivalent of Extended Iterable Unpacking operator is called spread syntax.

d = [...Array(7).keys()]
console.log(d)

var [a, ...b] = d
console.log(a,b)
Bluefarb answered 2/5, 2018 at 9:23 Comment(4)
So why this is correct: t = 1, *rest, but this not: t = *rest? The first one always automatically creates tuple?Cadmarr
t will hold the value for first element of d and rest of the values will be packed to rest variable.Bluefarb
The packed process will be produce in the left side of assignment.Bluefarb
but after printing 't' I receive all values not only the first one: (1, 2, 3), rest = [2, 3] t = 1, *rest print(t)Cadmarr
A
2

You can also use this:

>>> a,b,c,d,e,f,g = range(7)
>>> a
0
>>> b
1
>>> c
2
Alphanumeric answered 2/5, 2018 at 9:32 Comment(2)
sorry my bad, the range should be (7). this one will work: a,b,c,d,e,f,g = range(7)Alphanumeric
I'll take care of that, thanks for the guideline @PM2RingAlphanumeric
B
1

You don't appear to need the *

>>> z = [x for x in range(7)]
>>> a,b,c,d,e,f,g = z
>>> a
0
>>> b
1
>>> c
2
>>> 

(I've used z rather than d twice.)

Burgher answered 2/5, 2018 at 9:24 Comment(3)
Yeah, you're right, I didn't notice this double 'd'.Cadmarr
NP. The double 'd' isn't why unpacking fails. Also you don't actually need the auxiliary variable either: a,b,c,d,e,f,g = range(7) works because unpacking works on iterables.Burgher
Yeah, I see but double use of same identifier is not a good practice.Cadmarr

© 2022 - 2024 — McMap. All rights reserved.