Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Assigning 2 variables from one string

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

like image 622
Gabe Avatar asked Jun 10 '26 09:06

Gabe


2 Answers

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!

like image 135
Paulo Bu Avatar answered Jun 12 '26 22:06

Paulo Bu


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
like image 27
Eric Avatar answered Jun 12 '26 21:06

Eric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!