A tuple is a list that can no longer be changed.
Create a tuple
To create a tuple , you can use the following syntax:
>>> my_tuple = ()
Add a value to a tuple
To create a tuple with values, you can do it this way:
>>> my_tuple = ( 1 , "ok" , "olive tree" )
The parentheses are not mandatory but facilitate the readability of the code (remember that the strength of python is its ease of reading):
>>> my_tuple = 1 , 2 , 3 >>> type ( my_tuple ) < type 'tuple' >
When you create a tuple with a single value, remember to add a comma to it, otherwise it is not a tuple.
>>> my_tuple = ( "ok" ) >>> type ( my_tuple ) < type 'str' > >>> my_tuple = ( "ok" ,) >>> type ( my_tuple ) < type 'tuple' >
Display a value of a tuple
The tuple is kind of a list, so we can use the same syntax to read data from the tuple.
>>> my_tuple [ 0 ] 1
And obviously if we try to change the value of an index, the interpreter insults us copiously:
>>> mon_tuple [ 1 ] = "ok" Traceback ( most recent call last ): File "<stdin>" , line 1 , in < module > TypeError : 'tuple' object does not support item assignment
What is a tuple for then?
The tuple allows multiple assignment:
>>> v1 , v2 = 11 , 22 >>> v1 11 >>> v2 22
It also allows you to return several values when calling a function:
>>> def give_me_your_name (): ... return "olivier" , "engel" ... >>> give_me_your_name () ( 'olivier' , 'engel' )
We will use a tuple to define kinds of constants which are therefore not intended to change.
No comments:
Post a Comment