1

I'm reading about *args and **kwargs in Python, and am experimenting in the REPL:

varX, *varY = [99, 100, 101]

I was expecting varX to be [99, 100, 101], but that's not what happened. Instead I get this:

print(varX)
# 99

Huh? Well then what is varY?

print(varY)
# [100, 101]

Getting the list makes sense, but I thought it would have three values, and not two.

print(*varY)
# 100 101

At least this makes sense to me based on all of the stuff that's happened before. So my big question is why is Python (3.6) making the original assignments in this manner?

dawg
  • 98,345
  • 23
  • 131
  • 206
Alan W.
  • 353
  • 4
  • 13
  • 3
    It's called unpacking. You unpack a single value into `varX`, and then use the `*splat` operator to unpack everything else into `varY`. You could also use `x, y, z = [1,2,3]` to unpack each value of the list into each of your three variables. – user3483203 Aug 02 '18 at 13:45
  • 1
    See the PEP introducing this feature here: https://www.python.org/dev/peps/pep-3132/ – Patrick Haugh Aug 02 '18 at 13:45
  • 6
    Interesting. Your title and introduction have nothing to do with the meat of the question. Different type of unpacking. – Mad Physicist Aug 02 '18 at 13:45
  • 1
    Was expecting a question on functions when I saw the title – Adarsh Chavakula Aug 02 '18 at 14:00
  • I have to say, dupe hammer feels nice. Please let me know if the duplicate is missing something from what you want to know. – Mad Physicist Aug 02 '18 at 14:02

1 Answers1

0

To expand on what @user3483203 is trying to say - with some examples. You can pack and pack tuples into a single variable or unpack a tuple into several variables.

Say you have t = (1, 2, 3, 4, 5) you can unpack this by v, w, x, y, z = t this will assign each respecting index to the return variable so v = 1, w = 2 and so on. This is called unpacking "you are unpacking t into v, w, x, y, z. You can also pack variables together. Say you have v = 1, w = 2, x = 3, y = 4, z = 5 you can do the following t = [v, w, x, y, z].

This is just a brief explanation on packing and unpacking.

Ely Fialkoff
  • 642
  • 1
  • 5
  • 12