0

I stumbled upon a rather unconventional line of Python code recently and I'm curious to understand its purpose and implications. Here's the intriguing snippet:

*_, = "Python"

print(_)

Output:

['P', 'y', 't', 'h', 'o', 'n']

While I've got a decent grasp of Python, this syntax is a bit beyond my usual understanding. I've heard it's related to "extended unpacking", but how exactly does it work? Can someone shed light on what's happening step by step in this code? I'm especially interested in knowing why the variable is named _ and how this approach might be practically used. Is this a clever programming technique or just a creative way to obscure code?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Elie Hacen
  • 372
  • 12
  • 2
    Please update your question with what you know about the three characters: `*_,`. – quamrana Aug 21 '23 at 15:23
  • 1
    "Why the variable is named `_`" is completely arbitrary. It would work _more reliably_ with any other name, since `_` has special meaning in some contexts (most particularly the REPL). – Charles Duffy Aug 21 '23 at 15:26
  • I've never seen this syntax before. I only know about `*` but never seen with `_` and `,`. – Elie Hacen Aug 21 '23 at 15:26
  • 5
    Would you be less confused by `*othername, = "Python"` then? – Charles Duffy Aug 21 '23 at 15:27
  • `_` is "just" a variable name in Python. By convention (only), we use it to denote a variable we don't expect to use after assignment. – slothrop Aug 21 '23 at 15:27
  • 4
    Also, would you be less confused by `*varname, = [1, 2, 3]` ? i.e. is it iteration over strings that is part of the mystery here? – slothrop Aug 21 '23 at 15:28
  • 2
    Have you tried `*"Python",` or `_ = *"Python",`? – Elliott Frisch Aug 21 '23 at 15:28
  • 2
    @ElieHacen Do you know what `a, b, *c = sequence` means? This is the same thing, just with _everything_ being collected by `c`. See also [the original Extended Iterable Unpacking PEP](https://peps.python.org/pep-3132/). That PEP even explicitly brings up `*a, = range(5)` as an example – Brian61354270 Aug 21 '23 at 15:29
  • 2
    ...so if this _wasn't_ duplicative, it would be eligible for close by reason of being too broad; it munges together a bunch of other questions and fails to adequately distinguish which one(s) are being asked or to disambiguate from more focused queries on the individual subsets. – Charles Duffy Aug 21 '23 at 15:30

0 Answers0