Tuples in Python | Learn Python Programming Language
×

Tuples in Python

2636

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().



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments