Tuple in python

A tuple is a collection which is ordered and unchangeable

Tuple in python

A tuple is a list that can not be edited.

A tuple is a collection which is ordered and unchangeable

 

How to create a tuple?

To create a tuple, you can use the following syntax:

 

>>> my_tuple = ()

How to add a value to a tuple?

To create a tuple with values, you can do it this way:

 

>>> my_tuple = (1, "ok", "walid")

The parentheses are not necessary but simplify the readability of the code (remember that the strength of python is its simplicity of reading):

 

>>> my_tuple = 1, 2, 3

>>> type (my_tuple)

<type 'tuple'>

When you create a tuple with a single value, do not forget to add a comma to it, otherwise it is not a tuple.

>>> my_tuple = ("ok") # it is a string!

>>> type (my_tuple)

<type 'str'>

>>> my_tuple = ("ok",)

>>> type (my_tuple)

<type 'tuple'>

Display a value of a tuple

The tuple is a kind of list, so we can use the same syntax to read the tuple data.

>>> my_tuple [0]

1

And obviously if we try to change the value of an index, the interpreter shows us an error:

>>> my_tuple [1] = "ok"

Traceback (most recent call last):

  File "", line 1, in 

TypeError: 'tuple' object does not support item assignment

What is a tuple for?

The tuple allows multiple assignments:

>>> t1, t2 = 11, 22

>>> t1

11

>>> t2

22

It also allows you to return several values ​​when calling a function:

>>> def give_me_your_name ():

... return "walid", "jadla"

...

>>> give_me_your_name ()

('walid', 'jadla')

Tips: We can use a tuple to define constants which are not expected to change.

What's Your Reaction?

like
0
dislike
0
love
0
funny
0
angry
0
sad
0
wow
0