Tuples Eng
Tuples Eng
Characteristics of Tuple:
Creating Tuples:
Tuples can be created by placing the elements in parentheses (). Each value inside a tuple is
called an element or item. The elements in the tuple are separated by the commas (,).
Syntax:- tuple_name=()
tuple_name=(element 1,element 2,.....element n)
tuple_name=tuple()
tuple_name=tuple(sequence)
In python, we use tuple() method to create a tuple from tuple() method is also used to create a tuple through
an existing sequence keyboard
Sequence can be list, strings or tuples >>> a = tuple(input(“Enter the elements :”)
>>>list1 = [ 10,20,30 ]
>>> A2 = tuple(list1)
>>> A2
(10,20,30)
Traversing a tuple:
A tuple is a iterable. This means that we can use a for loop to traverse all the elements in the
tuple sequentially.
Example Output
A = (10 ,20, ”Srikanth”, 39.99) 10
20
for item in A: Srikanth
print(item) 39.99
T1 = ( 5, 2, 9, 7, 5, 8, 1, 4, 3 )
Example: Output
T1 = ( 5, 2, 9, 7, 5, 8, 1, 4, 3 )
print ( T1[3] ) 7
print ( T1[7] ) 4
t1= (10,20,30,40) 10
20
for i in range(0, len(t1) ) :
30
print( t1[i] )
40
i=i+1
Negative Indexing:
The negative index starts from last element and denotes by –1 , negative indices are used when
we want to access the elements of the tuple from right to left. Starting from right hand side, the
first element has the index as –1 and the last element has the index of –n where n is the length
of the tuple.
Positive Indices 0 1 2 3 4
Tuple 10 20 30 40 50
Negative Indices -5 -4 -3 -2 -1
Example: Output:
t = (10,20,30,40,50)
#print each element using index
50
print( t[-1] )
40
print( t[-2] )
30
print( t[-3] )
20
print( t[-4] )
10
print( t[-5] )
t =( 10 , 20, 30, 40 ) 40
30
for i in range(-1, -(len(t)+1), -1):
20
print ( t[i] )
10
Slicing
To access some part of a tuple, we use a method called slicing. The slicing operator [start :end]
is used for slicing. This can be done by specifying an index range, the slice operation tuple
[start : end] returns the part of the tuple starting from index start (inclusive) and ending at end
(exclusive). In other words, we can say that tuple[start :end] returns all the elements starting
from tuple[start] till tuple[end-1].
Positive Indices 0 1 2 3 4
Tuple 10 20 30 40 50
Example: Output
tuple =(10,20,30,40,50)
#This line of code will print tuple elements from 0th to 1st index
print(tuple[0:2])
(10,20)
#This line of code will print the elements from 1st to 2nd index
print(tuple[1:3])
#This line of code will print tuple elements from 1st to 4th index (20,30)
print(tuple[1:5])
(20,30,40,50)
Negative Slicing
We can also perform the slice operation on tuple using the negative index. The negative
indexing in tuple starts from the rightmost or last element present in the tuple. In the negative
slicing, we have to write negative index of tuple inside the slicing operator and between colon
operators to print the part of the tuple.
Tuple 10 20 30 40 50
Negative Indices -5 -4 -3 -2 -1
Example: Output
Examples: Output
#Step 2 indicates to consider every 2nd element, prints from 0th element to
7th element
print ( tuple[ 0 : 8 : 2 ] ) (10,30,50,70)
#Step –1 indicates to the slicing will starts from the end of the
String with one step back each time. It is like reversing tuple elements.
print (tuple [ : : -1 ] )
(80,70,60,50,40,30,20,10)
Concatenating two tuples means joining two types. We can concatenate two tuples using
concatenation operation plus which is denoted by symbol + .
1. Add two or more tuples and assign its values to a another tuple
2. Concatenate two or more tuples using printing output.
Example 1: concatenation using + operator Output
Repetition of tuples
Python allows us to repeat or replicate the elements of the tuple using repetition operator
which is denoted by symbol*. We can also assign the repetition value of a tuple to another
tuple.
Example: Output
tuple1=(10,20,30)
tuple2=tuple * 3
print(tuple2) (10,20,30,10,20,30,10,20,30)
We can check the membership of an element of the tuple using the membership operator. The
membership operators are used to check if a particular element belongs to the tuple or not.
Membership operators are of two types:-
Example: Output
2. ‘not in’ Membership operator: The ‘not in’ operator is also a tuple of membership
operator. It is used to check if particular element is not present in the tuple. The output
given ‘not in’ operator is also same of Boolean operators. It gives output as either true
or false. The ‘not in’ operator always gives opposite output of ‘in’ operator i.e., If ‘not in’
gives False then ’in’ operator will gives true in output or vice-versa.
Syntax: element ‘not in’ tuple
Example: Output
Greater than (>) operator : It checks whether the left value is >>> a = (1,2,3,4)
greater than that on the right >>> b = (5,2,3,4)
>>> a>b
False
Less than or Equal to (<=) Operator: This operator returns True only >>> a = (2,4,6,8)
when the value on the left is either less than or equal to that on the >>> b = (3,4,5,7)
right of the operator. >>> a<=b
True
Greater than or equal to (>=) operator: This operator returns True >>> a = (4,3,6,8)
only when the value on the right is either less than or equal to that >>> b = (2,5,4,3)
on the right of the operator. >>> a>=b
True
Equal to (==) operator: his operator return true, if the values on
either side of the operator are equal. >>> a = (2,3,4,6)
>>> b = (2,(3,4),6)
>>> c = (2,3,4,6)
>>> a==b
False
>>> a==c
True
Not equal (!=) operator: This operator return true, if the values on >>> a = (2,3,4,6)
the either side of the operator are not equal. >>> b = (2,(3,4),6)
True
4. Copying Tuple: To make a copy of the tuple is to assign a tuple to another tuple using
assignment operator (=).
Example Explanation
>>> tuple1 = (10 ,20, 30) The statement tuple2=tuple1 does not create a
>>> tuple2 = tuple1 new tuple. Rather, it just makes tuple1 and tuple2
>>>print (tuple2) refer to the same tuple object in the memory.
(10, 20, 30)
>>> print (tuple1) We can observe that the id of tuple1 and tuple2
(10, 20, 30) are same. There is only one tuple with two
>>> id (tuple1) references.
2343455465467
>>> id (tuple2)
2343455465467
Nested tuples : A tuple written inside another tuple is knows as a nested tuple.
Syntax:- Tuple_name = (value1, value2, (value3, value4, value5 ), value6, ...)
Example: Tuple=(10, 20, 30, 40, 50, 60, (100, 200, 300 ) )
The last element consisting of 3 elements written within parentheses is called a nested tuple as
it is inside another tuple.
Example Output
2. sum(): This method is used to calculate the sum of all >>> t = (10, 20, 30, 40, 50 )
the elements in the tuple. >>> sum ( t )
The sum() method is used for only numeric values 150
otherwise it gives an error(TypeError).
Syntax: sum(tuple_name)
3.max(): It is used to return the maximum element in the >>> t = (34, 76, 89, 33, 54, 65 )
tuple. >>> max ( t )
Syntax : max(tuple_name) 89
5.any(): The any() function return true if any of the >>> t = (10, 20, 0, 0, -30 )
Boolean values in the tuple is true. >>> any ( t )
Syntax: any(tuple_name) True
6.all(): The all() function returns true if all the Boolean >>> t = (10, 20, 0, 0, -30 )
values in the tuple are true, else returns false. >>> all ( t )
False
Syntax: all(tuple_name)
>>> t = (10, 20, 30, 40, ”Python”, 3.99 )
>>> all ( t )
True
7.Sorted(): The sorted() function returns a sorted list of >>> t1 = (20, 30, 40, 10, 50 )
>>> t2 = sorted ( t1 )
the specified iterable object. >>> print ( t2 )
[ 10, 20, 30, 40, 50 ]
To charge the sort order, we need to use “reverse= True” >>> t2 = sorted ( t1, reverse=True )
option with sorted() function. >>> print ( t2)
[ 50, 40, 30, 20, 10 ]
Tuple Methods:
Example Output
2. index(): The index() method searches for the given >>>t = (3, 5, 2, 6, ’hello’, 5 )
>>> t.index(5)
element from the start of the list and returns its index. 1
if the value appears more than once, it will return the >>> t.index(‘hello’)
index of the first one. If the item is not present in the 4
>>> t.index (9)
list then ValueError is thrown by this method. ValueError :tuple.index(x) : x not in tuple
Syntax: list.index(element)
The Zip() method in python takes one or more iterable( list,set,stringsetc) as arguments and
merges each of them element-wise to create a single iterable. The return value is a zip object,
which is also on iterable and consists of tuples.
This means that the first elements of all the input iterables are zipped together to the second
element of all the input iterables and so on.
The zip method maps the same index of multiple input iterables and converts them into a tuple.
The final zip objects can contain all the mapped tuples in the same order.
Syntax: zip ( iterable1, iterable2, iterable3,...)
Unzipping
There is no special function to unzip the zipped iterables, we can use the zip() method with the
* operator to unzip a zip object.
Example : Output
print (state_capital)
( (‘Karnataka’,’Benagluru’), (‘Orissa’,’Bhubaneswar’),
states_unzipped, capitals_unzipped = (‘Bihar’,‘Patna’), (‘Rajasthan’,’Jaipur’))
zip(*state_capital)
States are : (‘Karnataka’, ’ Orissa’, ‘Bihar’, ‘Rajasthan’)
print (“States are :”, states_unzipped)
person=("Snigdha”,25,”India”,”Karnataka”)
name, age, country, state = person
print(“Name :”, name) Name : Snigdha
print(“Age :”, age) Age : 25
print(“Country :”, country) Country : India
print(“State :”, state) State : Karnataka
Sometimes assigning every item from tuple to individual variable is not required. In those cases,
we can ignore them by using underscore (_).
Example: If we want to unpack only name and country only then code is :
Extended Unpacking: Sometimes it is required to unpack some specific items by skipping some
items from a tuple. In those cases, writing underscores (_) for every skipped item is not so
helpful. In such cases extended unpacking is very useful. It can done by using * as shown below:
Example Output
t = (10, 20, 30 )
print(t) (10, 20, 30)
del t
print(t) NameError: name ‘t’ is not defined
The tuple can be converted to list using list() function by passing tuple as an argument.
Once it is converted to the list, the contents in the list can be modified or altered.
Finally, we can convert the updated list into tuple by using tuple() function by passing
the updated list as an argument
Example Output
#create a tuple
languages = ("Python”, ”Java”, ”PHP”)
#print tuple contents Tuple Items: (‘Python’, ’Java’, ’PHP’)
print (“Tuple Items :”, Languages)
Lists have several built-in methods. A tuple does not have many built in methods because
it is immutable.
Lists are better for insertion and deletion operations. Tuple are appropriate for accessing the elements.
An unexpected change or error is more likely to occur In a tuple, changes or error don't usually occur
in a list. because of immutability.
List objects cannot be used as keys for dictionaries Tuple objects can be used as keys for dictionaries
because keys should be immutable. because keys should be mutable.
List consumes more memory than tuples. As lists are Tuples consume less memory than list. As tuples are
mutable, python needs to allocate an extra memory immutable and of a fixed size, python allocates only
block in case there is need to extend the size of the list the minimum memory block required for the data.
objects after we create it.
List can be copied. Tuples cannot be copied
# create a tuple
T1=( (1, “one”), (2,”two”), (3,”three”) )
Tuples are immutable. It cannot be altered or changed Dictionaries are mutable because we can add, delete,
after its creation. and changed the data values even after its creation.
Tuples allow duplicate values Dictionary keys do not allow duplicates. The values can
have duplicates.
An element cannot be added to the tuple as it is The update() method updates the dictionary with the
immutable. specified key-value pairs.
Tuple can be created using tuple() function. Dictionary can be created using dict() function.
The tuple element can be accessed by using index Dictionary works on key based indexing i.e. key
number. The index number starts from 0. identify the values.
Negative indexing and slicing is possible. No concept of negative indexing and slicing in
dictionary.