0% found this document useful (0 votes)
2 views9 pages

Notes

This document provides an overview of Python tuples, highlighting their immutable nature, creation methods, and various operations such as indexing, slicing, and concatenation. It includes examples of creating tuples, accessing elements, and using built-in functions like len(), max(), and min(). Additionally, it discusses tuple operations and limitations, such as the inability to modify or delete individual elements.

Uploaded by

Banpinder Singh
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)
2 views9 pages

Notes

This document provides an overview of Python tuples, highlighting their immutable nature, creation methods, and various operations such as indexing, slicing, and concatenation. It includes examples of creating tuples, accessing elements, and using built-in functions like len(), max(), and min(). Additionally, it discusses tuple operations and limitations, such as the inability to modify or delete individual elements.

Uploaded by

Banpinder Singh
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/ 9

CH-12 PYTHON TUPLES

TUPLES

A tuple is a sequence of comma separated values.

 Values in the tuple cannot be modified, i.e. it is immutable.


 The values that make up a tuple are called its elements.
 Elements in a tuple need not be of the same type.
 The comma separated values can be enclosed in parenthesis but parenthesis are not
mandatory.
 The index value of tuple starts from 0.

CREATING TUPLES

Tuples can be created by writing comma separated elements/values with or without parenthesis.

EXAMPLES
>>>tup1=('Sunday', 'Monday', 10, 20)
>>>tup2=('a', 'b', 'c', 'd', 'e')
>>> tup3=(1,2,3,4,5,6,7,8,9)
>>> tup4=(10,) # tuple with one element
>>>tup5=() # empty tuple

NOTE:

Here tup4 is a tuple with one single value. The final comma after single value is mandatory
otherwise it is not considered as tuple.
>>> tup6= (100)
>>> type(tup6)
<class 'int'>

Here tup6 is considered as integer not as tuple.


>>> tup6= (100,)
>>> type(tup6)
<class 'tuple'>

Now, tup6 is considered as a tuple.

tuple() function

An empty tuple can be created using tuple() function.

SYNTAX

tuple(iterable)

Here, the parameter iterable is optional. The iterable can be a string, list or dictionary. If the
iterable is not passed, empty tuple is created .
EXAMPLES

>>>tup7=tuple()

>>>print(tup7)

()
#creating a tuple from a string

>>>tup8=tuple(“Hello”)

>>>print(tup8)

('H', 'e', 'l', 'l', 'o')


#creating a tuple from a list

>>>tup9=tuple([10,20,30])

>>>print(tup9)

(10,20,30)
#creating a tuple from a dictionary

>>>tup10=tuple({1:10,2:20})

>>>print(tup10)

(1, 2)

CREATING A TUPLE FROM AN ALREADY EXISTING TUPLE

Consider the following tuples:


>>>tuple1=(100, 200, 300, 400, 500)
>>>tuple2=(90, 100, 200, 300,40)
>>>tuple3= ('A', 'E', 'I', 'O', 'U')
tuple5 is a copy of tuple1
>>>tuple5=tuple1[:]
tuple5=(100, 200, 300, 400, 500)
>>>tuple6=tuple2[1:4] >>>tuple6=tuple2[1:4]

tuple6 will contain elements 1,2,3 of tuple2

tuple6=(100, 200, 300)


>>>tuple7=tuple1 tuple7 will contain all elements of tuple1

tuple7=(100, 200, 300, 400, 500)


INITIALIZING TUPLE VALUES

We can initialize the tuple values using the following method:

EXAMPLE
>>> t=tuple()
>>> t=(10,)*10
>>> print(t)

OUTPUT
(10, 10, 10, 10, 10, 10, 10, 10, 10, 10)

ACCESSING TUPLE ELEMENTS

INDEXING METHOD

Elements of a tuple can be accessed using an indexing method.

 Tuple indices start at 0.


 The tuple index has to be a positive or negative integer value or an expression which
evaluates to an integer value. Positive value of index means counting forward from
beginning of the tuple and negative value means counting backward from end of the
tuple.
 An Index Error appears, if we try to access element that does not exist in the tuple.

If the total number of elements in the tuple is max, then:

Index value element in the list


0, -max 1st
1, -max+1 2nd
2, -max+2 3rd
........
max-2, -2 2nd last
max-1, -1 last

To access an element, present at a particular index square brackets along with the desired index
number is given.

SYNTAX

tuple-name [ index-number]

EXAMPLE 1
>>> t=('A', 'B', 'C')
>>> print(t[2])

OUTPUT
C
EXAMPLE 2
>>> t=('A', 'B', 'C')
>>> print(t[-2])

OUTPUT
B

EXAMPLE 3
>>> t=('A', 'B', 'C')
>>> print(t[2*1])

OUTPUT
C

TUPLE SLICING

Slicing is used to retrieve a subset of values. A slice of a tuple is basically its sub-tuple.

SYNTAX
tuple-name [start: stop: step]

where

start is the starting point

stop is the stopping point

step is the step size - also known as stride

NOTE:

 If you omit first index, slice starts from “0‟ and omitting of stop will take it to end.
Default value of step is 1.
 It includes the first element but excludes the last element.

EXAMPLE

Consider a tuple z1 with values


z1=(10,20,30,40,50,60)

z1[:] (10,20,30,40,50,60)
z1[2:5] (30,40,50)
z1[:5] (10,20,30,40,50)
z1[3:] (40,50,60)
z1[::2] (10,30,50) (from beginning till end in step 2)
z1[::-2] (60,40,20) (from end till beginning in step 2)
z1[-5:-2] (20,30,40)
z1[5:2:-1] (60,50,40)
z1[-2:-5:-1] (50,40,30)
z1[-2:-5:-2] (50,30)

ADDING ELEMENTS TO A TUPLE

'+' OPERATOR

New elements can be added to a tuple using '+' operator.

EXAMPLE 1
>>> t=tuple()
>>> t=t+(10,20)
>>> print(t)

OUTPUT
(10, 20)

EXAMPLE 2
>>> t=('A', 'B', 'C')
>>> t=t+ (10,)
>>> print(t)

OUTPUT
('A', 'B', 'C', 10)

NOTE : We can only add tuple to a tuple.

EXAMPLE 3
>>> t=('A', 'B', 'C')
>>> t=t+ 10

OUTPUT
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
t=t+ 10
TypeError: can only concatenate tuple (not "int") to tuple

ADDING NEW ELEMENTS USING LIST

To add new elements to a tuple using list follow these steps:


1. Convert tuple to list
2. Add elements to list using append function
3. After adding elements convert list to tuple

Consider the following code:


>>> tup1=tuple() #create empty tuple
>>> list1=list(tup1) #convert tuple into list
>>> list1.append(100) #Add new elements to list
>>> list1.append(200)
>>> tup1=tuple(list1) #convert list into tuple
>>> print (tup1)

OUTPUT
(100, 200)

UPDATING TUPLES

Tuples are immutable which means you cannot update or change the values of tuple elements.

DELETING TUPLE ELEMENTS

Removing individual tuple elements is not possible.

To explicitly remove an entire tuple, just use the del statement. For example
>>> del z1

NOTE : If we try to access a tuple after deleting it, it will result in error.
>>> print(z1)
Traceback (most recent call last):
File "<pyshell#66>", line 1, in <module>
print(z1)
NameError: name 'z1' is not defined

TUPLE OPERATIONS

Concatenation(+)

>>> (10, 20, 30) + (40, 50, 60)

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

>>> z2=(10, 20, 30, 40, 50, 60)

>>> z3=(30, 40)

>>> z4=z2+z3
>>> print(z4)

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


Repetition(*)

>>> ('true',) * 4

('true', 'true', 'true', 'true')

>>> z3=(30, 40)

>>> z3*2

(30, 40, 30, 40)


Membership(in, not in)

>>> 2 in (1, 2, 3)

True

>>> z2=(10, 20, 30, 40, 50, 60)

>>> 10 in z2

True
Iteration

for a in (1, 2, 3):

print(a,end=" ")

123
Swapping

>>> z2=(10, 20, 30, 40, 50, 60)

>>> z3=(30, 40)

>>> z2,z3=z3,z2

>>> print(z2)

(30, 40)

>>> print(z3)

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


TUPLE FUNCTIONS

EXPLANATION EXAMPLE
len() >>> tuple1=(100, 200, 50, 400, 500, 'Raman', 100,
'Ashwin')
Returns the length of the
tuple >>> len(tuple1)

SYNTAX: 9

len(tuple-name)
max() >>> tuple3=(10,20,30,40)

Returns the element with >>> max(tuple3)


maximum value from the
tuple 40

NOTE: To use the max() >>> tuple4=('A', 'a', 'B','C')


function all values in the
tuple must be of same >>> max(tuple4)
type
'a'

here it will return the alphabet with maximum ASCII value

>>> tuple5=('ashwin','bharat','shelly')

>>> max(tuple5)

'shelly'

here it will return the string which starts with character having
highest ASCII value.

>>> tuple5=('ashwin','bharat','shelly', 'surpreet')

>>> max(tuple5)

'surpreet'

If there are two or more string which start with the same
character, then the second character is compared and so on.
min() >>> tuple3=(10,20,30,40)

Returns the element with >>> min(tuple3)


minimum value from the
tuple 10

NOTE: To use the min() >>> tuple4=('A', 'a', 'B','C')


function all values in the
tuple must be of same >>> min(tuple4)
type
'A'
here it will return the alphabet with minimum ASCII value

>>> tuple5=('ashwin','bharat','shelly')

>>> min(tuple5)

'ashwin'

here it will return the string which starts with character having
smallest ASCII value.

>>> tuple5=('ashwin','bharat','shelly', 'surpreet')

>>> min(tuple5)

'ashwin'

If there are two or more string which start with the same
character, then the second character is compared and so on.
count() >>> tuple6=(10,20,10,30,10,40,50)

It is used to count the >>> tuple6.count(10)


occurrences of an item in
the tuple. 3
index(value) >>> tuple6=(10,20,10,30,10,40,50)

value: Required. The >>> tuple6.index(30)


value to search for
3
It is used to find the first
occurrence of the >>> tuple6.index(80)
specified value.
Traceback (most recent call last): File "<pyshell#3>", line
If the value is not found 1, in tuple6.index(80) ValueError: tuple.index(x): x not in
the index() method will tuple
raise an exception.
sorted() >>> tuple6=(10,20,10,30,10,40,50)

It is used to create a new >>> new=sorted(tuple6)


sorted list.
>>> print(new)
To sort in descending
order, set the argument [10, 10, 10, 20, 30, 40, 50]
reverse to True.
>>> print(sorted(tuple6, reverse=True))

[50, 40, 30, 20, 10, 10, 10]

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy