5

we can simply use:

crc = struct.unpack('>i', data)

why people like this:

(crc,) = struct.unpack('>i', data)

what does the comma mean?

Codefor
  • 1,238
  • 2
  • 12
  • 21

4 Answers4

11

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
NPE
  • 464,258
  • 100
  • 912
  • 987
2

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.

s1lence
  • 2,128
  • 2
  • 16
  • 32
1

The comma indicates crc is part of a tuple. (Interestingly, it is the comma(s), not the parentheses, that indicate tuples in Python.) (crc,) is a tuple with one element.

crc = struct.unpack('>i', data)

makes crc a tuple.

(crc,) = struct.unpack('>i', data)

assigns crc to the value of the first (and only) element in the tuple.

unutbu
  • 777,569
  • 165
  • 1,697
  • 1,613
1

(crc,) is considered a one-tuple.

Makoto
  • 100,191
  • 27
  • 181
  • 221