0% found this document useful (0 votes)
21 views

14 Tup Xi Methods

The document provides a comprehensive overview of Python tuples, including their definition, creation, and various built-in methods for manipulation. It covers operations such as concatenation, slicing, and searching, along with examples demonstrating tuple immutability and the use of functions like len(), max(), and min(). Additionally, it explains how to convert lists to tuples, access tuple elements, and perform basic operations.

Uploaded by

guru.s.shandilya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

14 Tup Xi Methods

The document provides a comprehensive overview of Python tuples, including their definition, creation, and various built-in methods for manipulation. It covers operations such as concatenation, slicing, and searching, along with examples demonstrating tuple immutability and the use of functions like len(), max(), and min(). Additionally, it explains how to convert lists to tuples, access tuple elements, and perform basic operations.

Uploaded by

guru.s.shandilya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

CLASS- XI , COMPUTER SCIENCE (2020-21)

CLASS-XI

Python Tuple Methods


Python has a set of built-in methods that you can use on Tuples.
Tuples: Definition, Creation of a Tuple, Traversal of a tuple. Operations on
a tuple - concatenation, repetition, membership; functions/methods –
len(), tuple(), count(), index(), sorted(), min(), max(), sum(); Nested tuple;
Tuple slicing; finding the minimum, maximum, mean of values stored in a
tuple; linear search on a tuple of numbers, counting the frequency of elements in a tuple.
Tuple
A tuple is a collection of objects which ordered and immutable. Tuples are sequences, just like
lists. The main difference between the tuples and the lists is that the tuples cannot be changed
unlike lists. Tuples use parentheses( ), whereas lists use square brackets[ ].
Ex.
A=(1,2,3,4,5,6)
B=(‘sun’,’mon’,’tue’)
C=( ) # empty tuple
D=(‘physics’,’chemistry’,’1999,2021)

Ex:

#use of tuple

a=(10,20,30,40)

b=(50,60,70)

c=('jan','feb',1999,2021)

print(a) #(10, 20, 30, 40)


print(b) #(50,60,70)

print(c) #('jan','feb',1999,2021)

print(a[1]) # 20

print(c[-3]) # feb

#a[1]=100 # not posssible because tuple is immutable

print(a+b)

#(10, 20, 30, 40, 50, 60, 70)

print(b+c)

#(50, 60, 70, 'jan', 'feb', 1999, 2021)

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

print(len(a)) # length of tuple

#4

#del a # delete the tuple

#print(a) now tuple a is not present

print(max(b))

#70

print(min(b))

#50
print(a.count(20))

#1

print(a.index(30))

#2

# Membership test in tuple

my_tuple = ('a', 'p', 'p', 'l', 'e',)

# In operation

print('a' in my_tuple)

#True

print('b' in my_tuple)

#False

# Not in operation

print('g' not in my_tuple)

#True

Ex:

# FIND MAXIMUM ELEMENT FROM TUPLE

A=(10,3,5,54,4,23,2)

b=A[0]

for i in A:

if i>b:

b=i

print("biggest value from tuple is",b)

Ex:

# FIND MAXIMUM ELEMENT FROM TUPLE


A=(10,3,5,54,4,23,2)

b=A[0]

l=len(A)

for i in range(l):

if A[i]>b:

b=A[i]

print("biggest value from tuple is",b)


Ex

# FIND MINIMUM ELEMENT FROM TUPLE

A=(10,3,5,54,4,23,2)

s=A[0]

for i in A:

if i<s:

s=i

print("Smallest value from tuple is",s)

Ex

# FIND MINIMUM ELEMENT FROM TUPLE

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]

print("Smallest value from tuple is",s)


Ex
# FIND sum and average of given TUPLE

A=(10,3,5,54,4,23,2)

s=0

for i in A:

s+=i

print("sum of the tuple is",s,"average",s/7)

Ex

# FIND the element from TUPLE(Linear search)

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:

print("given element is found",item)

else:

print("element is not present")

Ex

# count total element from TUPLE

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.

Accessing Values in Tuples


To access values in tuple, use the square brackets for slicing along with the index or indices to
obtain the value available at that index. For example −

A = ('physics', 'chemistry', 1997, 2000)


B = (1, 2, 3, 4, 5, 6, 7 )

print ("A[0]: ", A[0])


print ("B[1:5]: ", B[1:5])

When the above code is executed, it produces the following result −


A[0]: physics
B[1:5]: (2, 3, 4, 5)

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')

# Following action is not valid for tuples


# A[0] = 100;

# So let's create a new tuple as follows


C = A + B
print (C)

When the above code is executed, it produces the following result −


(12, 34.56, 'abc', 'xyz')

Delete Tuple Elements


Removing individual tuple elements is not possible. There is, of course, nothing wrong with
putting together another tuple with the undesired elements discarded.
To explicitly remove an entire tuple, just use the del statement. For example −

A = ('physics', 'chemistry', 1997, 2000);

print (A)
del A;
print ("After deleting A : ")
print (A)

This produces the following result.


Note − An exception is raised. This is because after del A, tuple does not exist any more.
('physics', 'chemistry', 1997, 2000)
After deleting A :
Traceback (most recent call last):
File "test.py", line 9, in <module>
print A;
NameError: name 'A' is not defined

Basic Tuples Operations


Tuples respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new tuple, not a string.
In fact, tuples respond to all of the general sequence operations we used on strings in the
previous chapter.

Python Expression Results Description

len((1, 2, 3)) 3 Length

(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation

('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition

3 in (1, 2, 3) True Membership


for x in (1,2,3) : print (x, end = ' ') 123 Iteration

Indexing, Slicing, and Matrixes


Since tuples are sequences, indexing and slicing work the same way for tuples as they do for
strings, assuming the following input −
T=('C++', 'Java', 'Python')

Python Expression Results Description

T[2] 'Python' Offsets start at zero

T[-2] 'Java' Negative: count from the right

Nesting of Tuples

# Code for creating nested tuples

tuple1 = (0, 1, 2, 3)

tuple2 = ('python', 'geek')

tuple3 = (tuple1, tuple2)

print(tuple3)

Output :
((0, 1, 2, 3), ('python', 'geek'))

Converting list to a Tuple


# Code for converting a list and a string into a tuple

list1 = [0, 1, 2]

print(tuple(list1))

print(tuple('python')) # string 'python'

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.

Built-in Tuple Functions


Python includes the following tuple functions −

Sr.No. Function & Description

1 cmp(tuple1, tuple2)

Compares elements of both tuples.

2 len(tuple)

Gives the total length of the tuple.

3 max(tuple)

Returns item from the tuple with max value.

4 min(tuple)

Returns item from the tuple with min value.


5 tuple(seq)

Converts a list into 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 () ,

separated by commas. The parentheses are optional, however, it is a good practice


to use them.
A tuple can have any number of items and they may be of different types (integer,
float, list, string, etc.).

# Different types of tuples

# Empty tuple
my_tuple = ()
print(my_tuple)

# Tuple having integers


my_tuple = (1, 2, 3)
print(my_tuple)

# tuple with mixed datatypes


my_tuple = (1, "Hello", 3.4)
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.

my_tuple = 3, 4.6, "dog"


print(my_tuple)

# tuple unpacking is also possible


a, b, c = my_tuple

print(a) # 3
print(b) # 4.6
print(c) # dog

Output

(3, 4.6, 'dog')


3
4.6
dog

Creating a tuple with one element is a bit tricky.

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'>

# Creating a tuple having one element


my_tuple = ("hello",)
print(type(my_tuple)) # <class 'tuple'>

# Parentheses is optional
my_tuple = "hello",
print(type(my_tuple)) # <class 'tuple'>

Output

<class 'str'>
<class 'tuple'>
<class 'tuple'>

Access Tuple Elements


There are various ways in which we can access the elements of a 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.

# Accessing tuple elements using indexing


my_tuple = ('p','e','r','m','i','t')

print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'

# IndexError: list index out of range


# print(my_tuple[6])

# Index must be an integer


# TypeError: list indices must be integers, not float
# my_tuple[2.0]

# 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

Python allows negative indexing for its sequences.

The index of -1 refers to the last item, -2 to the second last item and so on.

# Negative indexing for accessing tuple elements


my_tuple = ('p', 'e', 'r', 'm', 'i', 't')

# 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 : .

# Accessing tuple elements using slicing


my_tuple = ('p','r','o','g','r','a','m','i','z')

# elements 2nd to 4th


# Output: ('r', 'o', 'g')
print(my_tuple[1:4])
# elements beginning to 2nd
# Output: ('p', 'r')
print(my_tuple[:-7])

# elements 8th to end


# Output: ('i', 'z')
print(my_tuple[7:])

# elements beginning to end


# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple[:])

Output

('r', 'o', 'g')


('p', 'r')
('i', 'z')
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

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.

Element Slicing in Python

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.

We can also assign a tuple to different values (reassignment).

# Changing tuple values


my_tuple = (4, 2, 3, [6, 5])

# TypeError: 'tuple' object does not support item assignment


# my_tuple[1] = 9

# However, item of mutable element can be changed


my_tuple[3][0] = 9 # Output: (4, 2, 3, [9, 5])
print(my_tuple)

# Tuples can be reassigned


my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple)

Output

(4, 2, 3, [9, 5])


('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

We can use + operator to combine two tuples. This is called concatenation.


We can also repeat the elements in a tuple for a given number of times using
the * operator.
Both + and * operations result in a new tuple.

# 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 a tuple entirely, however, is possible using the keyword del.

# Deleting tuples
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

# can't delete items


# TypeError: 'tuple' object doesn't support item deletion
# del my_tuple[3]

# Can delete an entire tuple


del my_tuple

# NameError: name 'my_tuple' is not defined


print(my_tuple)

Output

Traceback (most recent call last):


File "<string>", line 12, in <module>
NameError: name 'my_tuple' is not defined

Tuple Methods
Methods that add items or remove items are not available with tuple. Only the
following two methods are available.

Some examples of Python tuple methods:

my_tuple = ('a', 'p', 'p', 'l', 'e',)


print(my_tuple.count('p')) # Output: 2
print(my_tuple.index('l')) # Output: 3

Output

2
3

Other Tuple Operations


1. Tuple Membership Test

We can test if an item exists in a tuple or not, using the keyword in .

# Membership test in tuple


my_tuple = ('a', 'p', 'p', 'l', 'e',)

# 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

2. Iterating Through a Tuple

We can use a for loop to iterate through each item in a tuple.

# Using a for loop to iterate through a tuple


for name in ('John', 'Kate'):
print("Hello", name)
Output

Hello John
Hello Kate

Advantages of Tuple over List

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

# Creating non-empty tuples

# Another for doing the same

tup = ('python', 'geeks')

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

# Code to create a tuple with repetition

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

#code to test that tuples are immutable


tuple1 = (0, 1, 2, 3)

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

# code to test slicing

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

# Code for deleting a tuple


tuple3 = ( 0, 1)

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

#python code for creating tuples in a loop

tup = ('geek',)

n = 5 #Number of time loop runs

for i in range(int(n)):

tup = (tup,)

print(tup)

Output :
(('geek',),)
((('geek',),),)
(((('geek',),),),)
((((('geek',),),),),)
(((((('geek',),),),),),)
Using cmp(), max() , min()

# A python program to demonstrate the use of

# cmp(), max(), min()

tuple1 = ('python', 'geek')

tuple2 = ('coder', 1)

if (cmp(tuple1, tuple2) != 0):

# cmp() returns 0 if matched, 1 when not tuple1

# is longer and -1 when tuple1 is shoter

print('Not the same')

else:

print('Same')

print ('Maximum element in tuples 1,2: ' +

str(max(tuple1)) + ',' +

str(max(tuple2)))

print ('Minimum element in tuples 1,2: ' +

str(min(tuple1)) + ',' + str(min(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.

You might also like