14 Tup Xi Methods
14 Tup Xi Methods
CLASS-XI
Ex:
#use of tuple
a=(10,20,30,40)
b=(50,60,70)
c=('jan','feb',1999,2021)
print(c) #('jan','feb',1999,2021)
print(a[1]) # 20
print(c[-3]) # feb
print(a+b)
print(b+c)
d=('hi')
print(d*2)
#hihi
50 in (10,20,30,40) #membership
for i in (10,20,30,40): # i in a:
print(i,end=' ')
#10 20 30 40
#4
print(max(b))
#70
print(min(b))
#50
print(a.count(20))
#1
print(a.index(30))
#2
# In operation
print('a' in my_tuple)
#True
print('b' in my_tuple)
#False
# Not in operation
#True
Ex:
A=(10,3,5,54,4,23,2)
b=A[0]
for i in A:
if i>b:
b=i
Ex:
b=A[0]
l=len(A)
for i in range(l):
if A[i]>b:
b=A[i]
A=(10,3,5,54,4,23,2)
s=A[0]
for i in A:
if i<s:
s=i
Ex
A=(10,3,5,54,4,23,2)
s=A[0]
l=len(A)
for i in range(l):
if A[i]<s:
s=A[i]
A=(10,3,5,54,4,23,2)
s=0
for i in A:
s+=i
Ex
A=(10,3,5,54,4,23,2)
item=int(input("element to be searched"))
flag=0
for i in A:
if i==item:
flag=1
break
if flag==1:
else:
Ex
A=(10,3,5,54,4,23,2)
count=0
for i in A:
count+=1
print("total element",count)
To write a tuple containing a single value you have to include a comma, even though there is
only one value −
tup1 = (50,)
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.
Updating Tuples
Tuples are immutable, which means you cannot update or change the values of tuple
elements. You are able to take portions of the existing tuples to create new tuples as the
following example demonstrates −
A = (12, 34.56)
B = ('abc', 'xyz')
print (A)
del A;
print ("After deleting A : ")
print (A)
Nesting of Tuples
tuple1 = (0, 1, 2, 3)
print(tuple3)
Output :
((0, 1, 2, 3), ('python', 'geek'))
list1 = [0, 1, 2]
print(tuple(list1))
Output
(0, 1, 2)
('p', 'y', 't', 'h', 'o', 'n')
Takes a single parameter which may be a list,string,set or even a dictionary( only keys are
taken as elements) and converts them to a tuple.
No Enclosing Delimiters
No enclosing Delimiters is any set of multiple objects, comma-separated, written without
identifying symbols, i.e., brackets for lists, parentheses for tuples, etc., default to tuples, as
indicated in these short examples.
1 cmp(tuple1, tuple2)
2 len(tuple)
3 max(tuple)
4 min(tuple)
A tuple in Python is similar to a list. The difference between the two is that we
cannot change the elements of a tuple once it is assigned whereas we can change
the elements of a list.
Creating a Tuple
A tuple is created by placing all the items (elements) inside parentheses () ,
# Empty tuple
my_tuple = ()
print(my_tuple)
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
Output
()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))
A tuple can also be created without using parentheses. This is known as tuple
packing.
print(a) # 3
print(b) # 4.6
print(c) # dog
Output
Having one element within parentheses is not enough. We will need a trailing
comma to indicate that it is, in fact, a tuple.
my_tuple = ("hello")
print(type(my_tuple)) # <class 'str'>
# Parentheses is optional
my_tuple = "hello",
print(type(my_tuple)) # <class 'tuple'>
Output
<class 'str'>
<class 'tuple'>
<class 'tuple'>
1. Indexing
We can use the index operator [] to access an item in a tuple, where the index
starts from 0.
So, a tuple having 6 elements will have indices from 0 to 5. Trying to access an
index outside of the tuple index range(6,7,... in this example) will raise an IndexError .
The index must be an integer, so we cannot use float or other types. This will result
in TypeError .
Likewise, nested tuples are accessed using nested indexing, as shown in the
example below.
print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'
# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
# nested index
print(n_tuple[0][3]) # 's'
print(n_tuple[1][1]) # 4
Output
p
t
s
4
2. Negative Indexing
The index of -1 refers to the last item, -2 to the second last item and so on.
# Output: 't'
print(my_tuple[-1])
# Output: 'p'
print(my_tuple[-6])
Output
t
p
3. Slicing
We can access a range of items in a tuple by using the slicing operator colon : .
Output
Slicing can be best visualized by considering the index to be between the elements
as shown below. So if we want to access a range, we need the index that will slice
the portion from the tuple.
Changing a Tuple
Unlike lists, tuples are immutable.
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.
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple)
Output
# Concatenation
# Output: (1, 2, 3, 4, 5, 6)
print((1, 2, 3) + (4, 5, 6))
# Repeat
# Output: ('Repeat', 'Repeat', 'Repeat')
print(("Repeat",) * 3)
Output
(1, 2, 3, 4, 5, 6)
('Repeat', 'Repeat', 'Repeat')
Deleting a Tuple
As discussed above, we cannot change the elements in a tuple. It means that we
cannot delete or remove items from a tuple.
# Deleting tuples
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
Output
Tuple Methods
Methods that add items or remove items are not available with tuple. Only the
following two methods are available.
Output
2
3
# In operation
print('a' in my_tuple)
print('b' in my_tuple)
# Not in operation
print('g' not in my_tuple)
Output
True
False
True
Hello John
Hello Kate
Since tuples are quite similar to lists, both of them are used in similar situations.
However, there are certain advantages of implementing a tuple over a list. Below
listed are some of the main advantages:
We generally use tuples for heterogeneous (different) data types and lists for
homogeneous (similar) data types.
Since tuples are immutable, iterating through a tuple is faster than with list. So there
is a slight performance boost.
Tuples that contain immutable elements can be used as a key for a dictionary. With
lists, this is not possible.
If you have data that doesn't change, implementing it as tuple will guarantee that it
remains write-protected.
Creating Tuples
# An empty tuple
empty_tuple = ()
print (empty_tuple)
Output:
()
print(tup)
Output
('python', 'geeks')
('python', 'geeks')
Note: In case your generating a tuple with a single element, make sure to add a comma after
the element.
Repetition in Tuples
tuple3 = ('python',)*3
print(tuple3)
Output
('python', 'python', 'python')
Try the above without a comma and check. You will get tuple3 as a string
‘pythonpythonpython’.
Immutable Tuples
tuple1[0] = 4
print(tuple1)
Output
Traceback (most recent call last):
File "e0eaddff843a8695575daec34506f126.py", line 3, in
tuple1[0]=4
TypeError: 'tuple' object does not support item assignment
Slicing in Tuples
tuple1 = (0 ,1, 2, 3)
print(tuple1[1:])
print(tuple1[::-1])
print(tuple1[2:4])
Output
(1, 2, 3)
(3, 2, 1, 0)
(2, 3)
Deleting a Tuple
del tuple3
print(tuple3)
Error:
Traceback (most recent call last):
File "d92694727db1dc9118a5250bf04dafbd.py", line 6, in <module>
print(tuple3)
NameError: name 'tuple3' is not defined
Output:
(0, 1)
Tuples in a loop
tup = ('geek',)
for i in range(int(n)):
tup = (tup,)
print(tup)
Output :
(('geek',),)
((('geek',),),)
(((('geek',),),),)
((((('geek',),),),),)
(((((('geek',),),),),),)
Using cmp(), max() , min()
tuple2 = ('coder', 1)
else:
print('Same')
str(max(tuple1)) + ',' +
str(max(tuple2)))
Output
Not the same
Maximum element in tuples 1,2: python,coder
Minimum element in tuples 1,2: geek,1
Note: max() and min() checks the based on ASCII values. If there are two strings in a tuple,
then the first different character in the strings are checked.