Tuples in Python

by Monika Dadool 24-Jan-19

0 627


Objects in python can be collected with the help of comma known as Tuple. It is identical to the list on the bases of some parameters like nested objects, indexing etc except that it is mutable i.e. fixed, unlike list. List in python can be modified. In python, tuples are written with the use of round brackets.

Syntax of tuple creation
tuplename =()
print(Tuplename)

Example
tupleexp1 = ("c", "c++","java","visualc++");
print(tupleexp1)

Output
('c', 'c++', 'java', 'visualc++')


Accessing
Items are referred through index number inside the square brackets in order to access them from the tuple.

Example

tupleexp1 = ("c", "c++","java","visualc++");
print(tupleexp1[3])

Output
visualc++


Iteration in Tuple
With the looping, one can easily iterate through the items present in the tuple and also print the values inside it. Given below the simple example of it.

Example
tupleexp1 = ("c", "c++", "java", "visualc++");
#print(tupleexp1[3])
for y in tupleexp1:
print(y)

Output
c
c++
java
visualc++


"in" keyword in Tuples
You can easily check the whether specified item is present in the tuple or not with the help of an in keyword.

Example
tupleexp1 = ("c", "c++", "java", "visualc++");
if "c" in tupleexp1:
  print("This language is present")

Output
This language is present


Nesting of Tuples

Example
tupleexp1 = ("c", "c++", "java", "visualc++");
tupleexp2 = ("c", "c++", "java", "visualc++");
tupleexp3 = ('python', 'geek')
tuple4 = (tupleexp1, tupleexp2, tupleexp3)
print(tuple4)

Output
(('c', 'c++', 'java', 'visualc++'), ('c', 'c++', 'java', 'visualc++'), ('python', 'geek'))


Repetition of Tuples

repititionexample = ('codingtag',)*9
print(repititionexample)

Output
('codingtag', 'codingtag', 'codingtag', 'codingtag', 'codingtag', 'codingtag', 'codingtag', 'codingtag', 'codingtag')

Tuple's constructor can be made with the help of double brackets.


del keyword
As tuple are immutable but we can delete entire tuple with the help of del keyword.

Example
repititionexample = ('codingtag',)*9
print(repititionexample)
del repititionexample
print(repititionexample)

Output
It will raise error because tuple will no more exists.


Inbuilt functions
Like inbuilt list functions, the tuple has also two inbuilt methods that can be used to operate tuple i.e. count() and index().


Share:


Comments

    Waiting for your comments

Leave a Reply