Wednesday 17 June 2020

Python Tuples


Understanding Tuples

Tuple is one of the built-in data structures or data types baked into Python, which is quite similar to Python Lists except with following features:

Immutable: Unlike lists, tuples are immutable; you cannot assign items after its creation. But tuple allows mutable types (lists) also and can be used to assign items for the mutable type only.

Creation: Tuples are created by enclosing items inside parenthesis” ( )” separated with commas or you can also create tuples without parenthesis. Simply, items separated with commas.

 Creating, indexing and slicing in Tuples

tuple = ( 1, 2, 3, 4, 5 )             

tuple

(1, 2, 3, 4, 5)

tuple[ 1 ]                             

2                

Tuple[ -1 ]

5

tuple[1 : 4 ]

( 2, 3, 4 )

To create a tuple with single item is little bit different, you simply cannot write like:

tuple = (1)  or  tuple = 1

type(t)

<class 'int'>

Because enclosing an item in parenthesis represents operator precedence in python expression  like (1) and python treats it  as integer and creates an object of class “int”. To make the python identify it as tuple’s item,  include a trailing comma (,)after the item like:

tuple = (1,)     or tuple = 1,

Tuples cannot be modified, they are Immutable

tuple = 1, 2, 6, 4, 5

tuple[2] = 3

Traceback (most recent call last):

  File "<pyshell#13>", line 1, in <module>

    tuple[2] = 3

TypeError:  'tuple' object does not support item assignment

 

But, tuples can have mutable types like lists and can be modified like:

tuple = (1, 2, 3, 4, [5, 9, 7, 8])      

tuple[4][1] = 6

tuple

(1, 2, 3, 4, [5, 6, 7, 8])

tuple[4] = [1, 2, 3, 4]

Traceback (most recent call last):

  File "<pyshell#9>", line 1, in <module>

    tuple[4] = [1, 2, 3, 4]

TypeError:  'tuple' object does not support item assignment

 

Tuple Packing

tuple = ( "lists", "sets", "dicts" )

Here, the items are packed into single object as tuple variable, is termed as tuple packing.


Tuple Unpacking

tuple = ( "lists", "sets", "dicts" )

x, y, z = tuple

x

‘lists’

y

‘sets’

z

‘dicts’

Here, tuple items are assigned into variables is termed as tuple unpacking.









For unpacking, the number of variables in left must be equal to number of values in tuple

y, z = tuple

Traceback (most recent call last):

  File "<pyshell#28>", line 1, in <module>

    y, z = tuple

ValueError: : too many values to unpack (expected 2)

 

 

 

17 comments: