6

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?

bad_coder
  • 11,289
  • 20
  • 44
  • 72
Codefor
  • 1,318
  • 2
  • 13
  • 22

4 Answers4

13

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
  • 486,780
  • 108
  • 951
  • 1,012
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,188
  • 2
  • 16
  • 34
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
  • 842,883
  • 184
  • 1,785
  • 1,677
1

(crc,) is considered a one-tuple.

Makoto
  • 104,088
  • 27
  • 192
  • 230