We can simply use:
crc = struct.unpack('>i', data)
why do people write it like this:
(crc,) = struct.unpack('>i', data)
What does the comma mean?
A comma forms a tuple, which in Python looks just like an immutable list. Python does destructuring assignment, found in a few other languages, e.g. modern JavaScript. In short, a single assignment can map several left-hand variables to the same number of right-hand values: foo, bar = 1, 2.
Unpacking in Python refers to an operation that consists of assigning an iterable of values to a tuple (or list ) of variables in a single assignment statement. As a complement, the term packing can be used when we collect several values in a single variable using the iterable unpacking operator, * .
Unpacking in Python refers to assigning values in an iterable object to a tuple or list of variables for later use. We can perform unpacking by using an asterisk ( * ) before the object we would like to unpack.
Summary. Unpacking assigns elements of the list to multiple variables. Use the asterisk (*) in front of a variable like this *variable_name to pack the leftover elements of a list into another list.
The first variant returns a single-element tuple:
In [13]: crc = struct.unpack('>i', '0000')
In [14]: crc
Out[14]: (808464432,)
To get to the value, you have to write crc[0]
.
The second variant unpacks the tuple, enabling you to write crc
instead of crc[0]
:
In [15]: (crc,) = struct.unpack('>i', '0000')
In [16]: crc
Out[16]: 808464432
the unpack
method returns a tuple of values. With the syntax you describe one can directly load the first value of the tuple into the variable crc
while the first example has a reference to the whole tuple and you would have to access the first value by writing crc[1]
later in the script.
So basically if you only want to use one of the return values you can use this method to directly load it in one variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With