1.

How do you unpack a Python tuple object?

Answer»

A tuple object is a collection data type. It contains one or more items of same or different data types. Tuple is DECLARED by LITERAL REPRESENTATION using parentheses to hold comma separated objects.

>>> tup=(10,'hello',3.25, 2+3j) Empty tuple is declared by empty parentheses >>> tup=()

However, single element tuple should have additional comma in the parentheses otherwise it becomes a single object.

>>> tup=(10,) >>> tup=(10) >>> type(tup) <class 'int'>

Using parentheses around comma separatedobjects is optional.

>>> tup=10,20,30 >>> type(tup) <class 'tuple'>

Assigning multiple objects to tuple is called packing. Unpacking on the other hand is extracting objects in tuple into individual objects. In above EXAMPLE, the tuple object contains three int objects. To unpack, three variables on LEFT hand side of assignment operator are used

>>> x,y,z=tup >>> x 10 >>> y 20 >>> z 30

Number of variables on left hand side must be equal to length of tuple object.

>>> x,y=tup Traceback (most recent call last):  File "<pyshell#12>", line 1, in <module>    x,y=tup ValueError: too many values to unpack (expected 2)

However, we can use variable prefixed with * to create list object out of remaining values

>>> x,*y=tup >>> x 10 >>> y [20, 30]


Discussion

No Comment Found