2

values is an array; eventTokens is a string (first element of values). What does the double assignment do? (What are the values of eventToken1 & eventToken2?)

values = data.split("\x01")

eventTokens = values.pop(0)
eventToken1, eventToken2 = eventTokens

I've done an output task (on the Python source) that resulted in the following:

eventTokens is →☹
eventToken1 is →
eventToken2 is ☹

I concluded that the vars somehow split the initial string. However, if I tried compiling an (apparently) similar thing:

arr = ["some", "elements", "inarray"]
c = arr.pop(0)
a, b = c
print c
print a
print b

It resulted in an exception: ValueError: too many values to unpack .

Note: print is not a parameterized method in the tested environment

3 Answers 3

3

Variable unpacking is the Python's ability of multiple variable assignment in a single line. The constraint is that the iterable on right side of the expression have to be the same lenght of the variables on the left side. Otherwise you get a too many or to little values to unpack exception.

If you have a string of size 2 like eventTokens is supposed to be, you can then:

>>>a,b = 'ab'
>>>a
'a'
>>>b
'b'

This is very unsafe code. If somehow eventTokens grows larger than two elements the code will raise an exception an your program will be shut down.

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

3

Since eventTokens is a string of length two, it can be unpacked into two single character strings:

>>> a, b = 'ab'
>>> a
'a'
>>> b
'b'

However, the number of characters in the string must match the number of variables being unpacked into:

>>> a, b = 'abcd'
ValueError: too many values to unpack

Note that you can unpack into one variable!

>>> a, = 'x'
>>> a
'x'
>>> a, = 'xyz'
ValueError: too many values to unpack

Comments

3

c = arr.pop(0) returns "some" here, but you are trying to assign the value to 2 variables in this step (where are there are 4 literals) hence, a, b = c is failing.

Try this instead

arr = ["some", "elements", "inarray"]
c = arr.pop(0)
a, b = arr
print c
print a
print b

4 Comments

This answer is not correct. The reason you get the "too many values to unpack" error is because c has four characters, and you're trying to unpack it into just two variables. a, b, d, e = c would work.
@Jimothy I believe OP wants a, b = arr and not a, b = c , So this example works
you're right. I should have said your explanation of why a, b = c gives an error is incorrect.
@Jimothy Thanks. Rectified.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.