Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does the comma mean in python's unpack?

Tags:

python

unpack

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?

like image 754
Codefor Avatar asked Dec 15 '12 17:12

Codefor


People also ask

What does comma represent in Python?

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.

What does unpack mean in Python?

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, * .

How do you unpack an object in Python?

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.

How do you unpack a list in Python?

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.


2 Answers

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
like image 120
NPE Avatar answered Oct 10 '22 04:10

NPE


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.

like image 43
s1lence Avatar answered Oct 10 '22 06:10

s1lence