Python 04uple
Python 04uple
Python 04uple
Create a tuple
Output :
You can access tuple items by referring to the index number, inside square
brackets:
Output :
Change Tuple Values
Example
You can loop through the tuple items by using a for loop.
Output :
apple
banana
cherry
Output :
Add Items
Tuples are unchangeable, so you cannot remove items from it, but you can
delete the tuple completely:
Tuples are immutable,that’s why we can’t change the content of tuple.It’s alternate way is to
take contents of existing tuple and create another tuple with these contents as well as new
content.
print (tup3)
Direct deletion of tuple element is not possible but shifting of required content after discard of
unwanted content to another tuple.
print (tup3)
Output (1, 3)
Tuple Methods
(a) Count – Returns the number of times a specified value occurs in a tuple
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = thistuple.count(5)
print(x)
Output : 2
(b) index - Searches the tuple for a specified value and returns the position
of where it was found.
Search for the first occurrence of the value 8, and return its position:
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = thistuple.index(8)
print(x)
Output : 3
Output : 3
Example:
Tuple = (456,700,200)
Example:
Tuple = (456,700,200)
Python tuple is an immutable object. Hence any operation that tries to modify it (like append) is not allowed.
However, following workaround can be used.
First, convert tuple to list by built-in function list(). You can always append item to list object. Then use
another built-in function tuple() to convert this list object back to tuple.
>>> T1=(10,50,20,9,40,25,60,30,1,56)
>>> L1=list(T1)
>>> L1
>>> L1.append(100)
>>> T1=tuple(L1)
>>> T1
Exercises
3. Write a Python program to create a tuple with numbers and print one item.
5. Write a Python program to get the 4th element and 4th element from last of a tuple.
Practice questions