Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
120 views

Tuple in Python PDF

The document discusses tuples in Python. Some key points: 1) Tuples are immutable ordered sequences of elements like lists but cannot be changed once created. Tuples use parentheses while lists use brackets. 2) Tuples can be created using parentheses, the tuple() function, or without parentheses by "packing". Elements can be accessed and iterated over using indexes and for loops. 3) The + operator concatenates tuples while * replicates tuples. The in operator checks membership. Tuples are immutable so their elements cannot be changed, unlike lists.

Uploaded by

Ashutosh Trivedi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
120 views

Tuple in Python PDF

The document discusses tuples in Python. Some key points: 1) Tuples are immutable ordered sequences of elements like lists but cannot be changed once created. Tuples use parentheses while lists use brackets. 2) Tuples can be created using parentheses, the tuple() function, or without parentheses by "packing". Elements can be accessed and iterated over using indexes and for loops. 3) The + operator concatenates tuples while * replicates tuples. The in operator checks membership. Tuples are immutable so their elements cannot be changed, unlike lists.

Uploaded by

Ashutosh Trivedi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Tuple Data Type In Python:

▪ Tuple data type is exactly same as list data type except that it is
immutable, we cannot change values.
▪ It is fixed-length and immutable.
▪ The values in the tuple cannot be changed nor the values be added
to or removed from the tuple
▪ Tuple elements can be represented within parenthesis.
▪ Tuple Can be made using the parentheses.
▪ Lists are enclosed in brackets [ ] and their elements and size can be
changed, while tuples are enclosed in parentheses ( ) and cannot be
updated. Tuples are immutable.
Difference Between List and Tuple
List Tuple
List is used for holding multiple Tuple is also used for holding
element. multiple element.
heterogeneous objects are allowed heterogeneous objects also are
in List allowed in Tuple.

duplicates are allowed in List. duplicates are allowed In Tuple.

List is Growable in nature Tuple is fixed-length in nature

List is a mutable type object Tuple is an immutable type object


In List, values should be enclosed In Tuple, values should be
within square brackets []. enclosed within parentheses ().

Different Ways to Creating a Tuple in Python


▪ tuple Can be made using the parentheses.
▪ We can create a tuple by placing values with-in parentheses and
values should be separated by comma.
my_tuple=(value1,value2,value3,.....valuen)
my_tuple=(10,20,30)
print(my_tuple)

❖ We can create empty tuple object as follows.

▪ We can create an empty tuple with-out placing any value with-in


parentheses.
# Empty tuple
my_tuple = ()
print(my_tuple) # Output: ()
❖ We can create tuple object with some element as follows.
# Tuple having integers
my_tuple = (10, 20, 30,40,50)
print(my_tuple) # Output: (10, 20, 30, 40, 50)

# tuple with mixed datatypes


my_tuple = (10, "Hello", 5.6)
print(my_tuple) # Output: (10, 'Hello', 5.6)

❖ We can create tuple object with-out parentheses also as


follows.
Packing Tuples
▪ Tuple can be made without using brackets also This is known as
tuple packing.
▪ We can say that a tuple is a comma-separated list of values:

my_tuple=value1, value2, value3, valuen


▪ The assignment a = 1, 2, 3 is also called packing because it packs
values together in a tuple.

my_tuple=10,20,30
print(my_tuple)#The Output (10, 20, 30)

Unpacking Tuples
▪ To unpack values from a tuple and do multiple
assignments use
# tuple unpacking is also possible
a,b,c=(10,20,30)
print(a)#The Output 10
print(b)#The Output 20
print(c)#The Output 30
Note:-
▪ The symbol _ can be used as a disposable variable name if one only
needs some elements of a tuple, acting as a placeholder.
a = 1, 2, 3, 4
_, x, y, _ = a
print(_)# The output 4
print(x)# The output 2
print(y)# The output 3
print(_)# The output 4

Can we create a tuple with single element?


▪ It is a bit tricky to make a tuple with a single element.

my_tuple=(10)
print(my_tuple)#The Output 10
print(type(my_tuple))#The Output <class 'int'>

my_tuple=('hello')
print(my_tuple)#The Output hello
print(type(my_tuple))#The Output <class 'str'>
Note:-
▪ A single value in parentheses is not a tuple
▪ Keeping only one value is not enough within the tuple We will
need a trailing comma to indicate tuple.
▪ you have to include a final comma
my_tuple=(10,)
print(my_tuple)#The Output (10,)
print(type(my_tuple))#The Output <class 'tuple'>

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

Single element tuples:


x, =1,
print(x) #The Output 1
print(type(x)) #The Output <class 'int'>

y=1,
print(y)#The Output (1,)
print(type(y)) #The Output <class 'tuple'>

❖ We can create tuple object with tuple() function as follows.

▪ The tuple() function creates a tuple from an iterable object.


▪ An iterable may be either a sequence, a container that supports
iteration.
my_tuple=tuple()
print(my_tuple)#The Output ()
#Create an tuple by passing string as a sequence
my_tuple=tuple('hello')
print(my_tuple)#The Output ('h', 'e', 'l', 'l', 'o')

How to access Element from the Tuple


▪ The elements of a tuple can be accessed via an index, or numeric
representation of their position. Lists in Python are zero-indexed meaning
that the first element in the list is at index 0, the second element is at index 1
and so on:
▪ Accessing tuple elements using positive indexes
nums=(10,20,30,40,50)
print(nums[0])#The Output 10
print(nums[1])#The Output 20
print(nums[2])#The Output 30
print(nums[3])#The Output 40
print(nums[4])#The Output 50
Note:
▪ TypeError:
If you do not use integer indexes in the tuple. For example
my_data[2.0] will raise this error. The index must always be an
integer.

▪ IndexError:
Index out of range. This error occurs when we mention the index
which is not in the range. For example, if a tuple has 5 elements
and we try to access the 7th element then this error would occurr.

▪ Accessing tuple elements using negative indexes


▪ Indices can also be negative which means counting from the end of the list (-
1 being the index of the last element).

nums=(10,20,30,40,50)
print(nums[-1])#The Output 50
print(nums[-2])#The Output 40
print(nums[-3])#The Output 30
print(nums[-4])#The Output 20
print(nums[-5])#The Output 10

Iterating Through a Tuple


▪ Using a for loop we can iterate through each item in a tuple.
nums=(10,20,30,40,50)
for n in nums:
print(n)

▪ You can also get the position of each item at the same time Using
enumerate function:
nums=(10,20,30,40,50)
for (index, item) in enumerate(nums):
print('The item in position {} is: {}'.format(index, item))

Output:
The item in position 0 is: 1
The item in position 1 is: 2
The item in position 2 is: 3
The item in position 3 is: 4
The item in position 4 is: 5
The item in position 5 is: 6

▪ The other way of iterating a tuple based on the index value:


nums=(10,20,30,40,50)
for i in range(0,len(nums)):
print(i,'->',nums[i])
Output:
0 -> 1
1 -> 2
2 -> 3
3 -> 4
4 -> 5
5 -> 6

Tuple Operators In Python


The + Operator
▪ The + operator is Used to concatenating to tuple.
▪ The simplest way to concatenate tuple1 and tuple2
merged = tuple1 + tuple2
tuple1=(10,20,30)
tuple2=(40,50)
merge_tuple=tuple1+tuple2
print('tuple1 =',tuple1)
print('tuple2 =',tuple2)
print('merge_tuple= ',merge_tuple)
Output:
tuple1 = (10, 20, 30)
tuple2 = (40, 50)
merge_tuple= (10, 20, 30, 40, 50)
tuple1=(10,20,30)
tuple2=(40,50,60)
for a, b in zip(tuple1, tuple2):
print(a, b)

The * Operator
▪ The * operator creates multiple copies of a string.
▪ Replication – multiplying an existing tuple by an integer will produce a
larger tuple consisting of that many copies of the original.

tuple1=(10,20,30)
print(tuple1*3)
tuple2=('a','b','c')
print(tuple2*3)
Output:
(10, 20, 30, 10, 20, 30, 10, 20, 30)
('a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c')

The in Operator
Checking Membership(Tuple Contains):
▪ By using in operator, we can check whether an item is in a tuple or not.
tuple1=(10,20,30)
print(10 in tuple1)# The Output True
print(10 not in tuple1)# The Output False
print(40 not in tuple1)# The Output True
tuple2=('a','b','c')
print('a' in tuple2)# The Output True
print('a' not in tuple2)# The Output False
print('d' not in tuple2)# The Output True

Tuples are immutable


▪ There is a major difference between lists and tuples in python is that tuples
are immutable i.e. tuple can't be modifying once they have to initialized that
is add or modify items from the tuple is not allowed once the tuple is
initialized.

tuple1=(10,20,30,40,50)
tuple1[0]=60
print(tuple1)
tuple1[0] =60
TypeError: 'tuple' object does not support item assignment

Important Ponts:

▪ If all of the elements present in the tuple are of the immutable


type, then no element of the tuple can be changed. but if any
element is of the mutable type like list, then that element of a
tuple can be changed.
tuple1=(10,20,30,40,50)
tuple1[0]=60
tuple1[0]=60
TypeError: 'tuple' object does not support item assignment

▪ We cannot change this tuple because all the elements present


in it are of an immutable type.

tuple1= (10,20,30, [40,50])


tuple1[3][0] =60
print(tuple1) #The Output (10, 20, 30, [60, 50])
▪ In this tuple there is a list object at 3 positions which is
immutable type, so we can change the 3 elements of the
tuple.
tuple1=(10,20,30,[40,50])
tuple1[3].append(60)
print(tuple1)

Similarly, tuples don't have. append and. extend methods as list


does.
tuple1=(10,20,30,40,50)
tuple2=tuple1.append(60)
print(tuple2)

tuple2=tuple1.append(60)
AttributeError: 'tuple' object has no attribute 'append'

tuple1=(10,20,30)
tuple2=(40,50,60)
tuple3=tuple1.extend(tuple2)
print(tuple3)

tuple3=tuple1.extend(tuple2)
AttributeError: 'tuple' object has no attribute 'extend'

Deleting a Tuple in Python

▪ We already discussed, that tuple elements are immutable i.e we


cannot change the elements in a tuple. That also means we cannot
delete or remove items from a tuple.
▪ However, deleting entire tuple is possible using the keyword del.

my_tuple = (10,20,30,40,50)
del my_tuple[3]
print(my_tuple)

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

my_tuple = (10,20,30,40,50)
# Can delete an entire tuple
del my_tuple
# NameError: name 'my_tuple' is not defined
print(my_tuple)

print(my_tuple)
NameError: name 'my_tuple' is not defined
Tuple Method

Count() method in Tuple


▪ count () method tell how many times an element is occurrence in a
tuple. So, count () method returns the occurrence of an element in a
list.
▪ The count () method takes a single parameter.
tuple.count(element)
element - element whose count is to be found

Example 1: counting an element in a tuple


tuple1=[10,20,10,10,30,20]
n=int(input('enter element'))
c=tuple1.count(10)
print(n,' occur' ,c,'times')

Example 2: counting a list in a tuple

tuple1=([10,20],[30,40],[10,20],[50,60])
list1=eval(input('enter list for count'))
c=tuple1.count(list1)
print(list1,' occur' ,c,'times')
Tuple Length
▪ The function len returns the total length of the tuple
tuple1= (10,20,30,40,50)
print('Length of Tuple=',len(tuple1))#The Output Length of Tuple= 5

Max of a tuple
▪ The function max returns item from the tuple with the max value
tuple1= (10,20,30,40,50)
print ('Max of Tuple= ‘, max(tuple1)) #Max of Tuple= 50

Min of a tuple
▪ The function min returns the item from the tuple with the min
value.
tuple1= (10,20,30,40,50)
print ('Min of Tuple= ‘, min(tuple1)) #Min of Tuple= 50
Convert a list into tuple
▪ The built-in function tuple converts a list into a tuple.
list1=[10,20,30,40,50]
tuple1=tuple(list1)
print(list1)
print(tuple1)
#The Output
[10, 20, 30, 40, 50]
(10, 20, 30, 40, 50)

Slicing of a Tuple (selecting parts of lists)


▪ Slicing of a Tuple means selecting a part of a tuple.
tuple[beginindex:endindex:step]
▪ from begin index to end-1 index and every time update by step
▪ default value for begin index is zero.
▪ default value for end index is length of string.

tuple[begin:end:step]
▪ step value can be either +ve or -ve.
▪ if +ve then it should be forward direction (Left to Right).
▪ If -ve then it should be backward direction (Right to Left).
▪ If +ve forward direction from begin to end-1.
▪ if -ve backward direction from begin to end+1.

Selecting a subtuple from a tuple.


tuple1=(10,20,30,40,50,60,70)
print(tuple1[1:4])#The OutPut (20, 30, 4)
print(tuple1[3:7]);#The OutPut (40, 50, 60, 70)

❖ If you omit the first index, the slice starts at the beginning of the
tuple. Thus, tuple[:m] and tuple[0:m] are equivalent:
tuple[:endindex]
tuple1=(10,20,30,40,50,60,70)
print(tuple1[:2])#The OutPut (10, 20)
print(tuple1[:3]);#The OutPut (10, 20, 30)

❖ if you omit the second index as in s[n:], the slice extends from the
first index through the end of the list. This is a nice, concise
alternative to the more cumbersome s[n:len(s)]:
tuple[beginindex:]
tuple1=(10,20,30,40,50,60,70)
print(tuple1[5:])#The OutPut (60, 70)
print(tuple1[6:]);#The OutPut (70,)

❖ If you Omitting both indices return the original tuple.


tuple[:]
tuple1=(10,20,30,40,50,60,70)
print(tuple1[:])#The OutPut(10, 20, 30, 40, 50, 60, 70)
❖ If the first index in a slice is greater than or equal to the second
index, Python returns an empty tuple.
tuple1=(10,20,30,40,50,60,70)
print(tuple1[2:2])#The OutPut ()
print(tuple1[4:2]);#The OutPut ()

❖ Reversing a tuple with slicing


a = (10, 20, 30, 40, 50)
# steps through the tuple backwards (step=-1)
b = a[::-1]
print('Original List=',a)
print('Reverse List= ',b)

Appending an element in tuple

Suppose we have a tuple i.e.


my_tuple=(10,20,30,40)

▪ If we want to append the value at the end of the tuple, then first we
have to make copy of existing tuple and then add new element to it
using + operator.

#Appending 50 at the end of tuple


my_tuple=my_tuple+(50,)

▪ And then we will put the address of the newly created tuple in
the original reference
▪ hence it will give an effect that new element is added to existing
tuple.
print(my_tuple)
Program
my_tuple=(10,20,30,40)
print(my_tuple)#The Output (10, 20, 30, 40)
#Appending 50 at the end of tuple
my_tuple=my_tuple+(50,)
print(my_tuple)#The Output (10, 20, 30, 40, 50)

Inserting an element at specific index in tuple

▪ If we want to insert an element at a specific index position in the existing tuple


then first off all we have to create a new tuple by slicing the existing tuple and
copying contents from it.
Suppose we have a tuple i.e.
# Create a tuple
tuple1 = (10,20,30,50)
▪ If we want to insert an element at index n in this tuple, then we will create
two sliced copies of existing tuple from (0 to n) and (n to end) i.e.
# Sliced copy containing elements from 0 to n-1
tupleObj[ : n]
# Sliced copy containing elements from n to end
tupleObj[n : ]

# Create a tuple
my_tuple = (10,20,30,50)

n=3
# Insert 40 in tuple at index 2
my_tuple = my_tuple[ : n ] + (40 ,) + my_tuple[n : ]

print(my_tuple)#The Output (10, 20, 30, 40, 50)


Modify / Replace the element at specific index in tuple

▪ If we want to Modify / Replace the element at a specific index


position in the existing tuple we will slice the tuple from (0 to n-1) and
(n+1 to end) i.e.

tuple=tuple [: n] +(value,) +tuple[n+1:]

# Create a tuple
my_tuple = (10,20,30,40,50)

n=3
# Insert 40 in tuple at index 2
my_tuple = my_tuple[ : n ] + (40 ,) + my_tuple[n+1 : ]

print(my_tuple)#The Output (10, 20, 30, 40, 50)

Delete an element at specific index in tuple


▪ If we want to Modify / Replace the element at a specific index position in
the existing tuple we will slice the tuple from (0 to n-1) and (n+1 to end)
i.e.
tuple=tuple [: n] +tuple[n+1:]

# Create a tuple
my_tuple = (10,20,30,50)

n=3
# Insert 40 in tuple at index 2
my_tuple = my_tuple[ : n ] + my_tuple[n+1 : ]

print(my_tuple)#The Output (10, 20, 30, 50)

You might also like