In this post, we will see what is the tuple, how its different from the list, how we can create them and iterate to use them.

What is tuple

In python, a tuple is seal packet of data container which could store different elements, as said they are seal package we can’t change them or their elements after creation.

Diffrent from list

they consume less memory and faster as compared to the list, which makes it perform better than. We can also use them as dictionary key as its static, on other hands we can’t use the list as they are mutable.

Simple tuple could create in below way. Assign a variable to contain element separate through comma (,) and wrapped through braces

Create tuple

>>> tuple1=('linux','windows','Mac','android')

>>> type(tuple1)
<type 'tuple>

>>> print tuple1
('linux', 'windows', 'Mac', 'android')

Creating tuple without braces

we could also do same without braces or unpacked.

>>> tuple2='Redhat','CentOS','Fefora','Ubuntu','Debian'

>>> type(tuple2)
<type 'tuple>

>>> print tuple2
('Redhat', 'CentOS', 'Fefora', 'Ubuntu', 'Debian')

Empty tuple

We can also create an empty tuple, although empty tuple is used to check the status of the variable.

>>> empty_tuple=()

>>> type(empty_tuple)
<type 'tuple>

>>> print (any(empty_tuple))

Empty tuple will always come with false status with any function as used above.

Use list as tuple

We could also use list as tuple like below.

>>> list=range(10)

>>> list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> type(list)
<type 'list>

>>> tuple4=tuple(list)

>>> type(tuple4)
<type 'tuple>

>>> print tuple4
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

Iterate Over tuple

we could iterate over tuple through for loop just like any other container.

>>> tuple1=('linux','windows','Mac','android')

>>> type(tuple1)
<type 'tuple>

>>> for elem in tuple1:
...  print elem