Tuple is a sequence of data similar to list. But it is immutable.
Data in a tuple is written using parentheses and commas.
tuple can contain any number of elements and elements can be int,float,string,list.
List index starts from 0.
Creating tuple
- tuples can be created by placing all elements inside the parentheses, separated by commas(,).
- without parentheses also we are able to create tuple.
a = ()#empty tuple
print(a)
a = (1,2,3,4,5)#integer Type
print(a)
a = (1,”Hello”,3,”Hi”,5) #Mixed type
print(a)
a = 1,”ss”,3,5
print(a)
Creating a tuple with one element is a bit tricky.
a = (“Hello”)
print(a)
print(type(a))
a = (“Hello”,)
print(a)
print(type(a))
a = (1)
print(a)
print(type(a))
a = (1,)
print(a)
print(type(a))
Accessing Tuple element:
- Indexing
a = (“a”,1,(11,22,44),[“aa”,”bb”,”cc”])
print(a[0])
print(a[2])
- Nested Indexing
print(a[2][0])
print(a[0][0])
-Negative Indexing
print(a[-1])
print(a[-1][-1])
Slicing
a = [‘a’,’b’,’c’,’d’,’e’,’f’,’g’,’h’,’i’]
print(a[:])
print(a[0:1])
print(a[0:2])
print(a[0:-7])
print(a[:-7])
print(a[7:-1])
Changing Tuple
- This means that elements of a tuple cannot be changed once they have been assigned. But, if the element is itself a mutable data type like list, its nested items can be changed.
a = (“a”,33,[11,22,33,44])
a[2][1] = 21
print(a)
a[0] = “c”
+ and * operator
a = (22,34,"xx") + ("ss",55,22)
print(a)
a = (("aa",)*3)
print(a)
Deleting Tuple
del a
print(a)
Tuple Methods
1. count():
- get the number of times a given element is available in tuple.
-count(ele)
a = (11,44,11,55,[11,66,77,88])
print(a.count(11))
2.index():
- This method returns the index of a given element.
- index(ele)
print(a.index(11))
print(a.index(99))
Membership Operator
print(11 in a)
print(99 in a)
print(99 not in a)
Iterating
for x in a:
print(x)