PYTHON
TUPLES
Class
TUPLES:
A tuple is a collection of objects which ordered and immutable. Tuples are sequences, just
like lists. The differences between tuples and lists are, the tuples cannot be changed unlike
lists and tuples use parentheses, whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values. Optionally you
can put these comma-separated values between parentheses also.
Example:
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
Accessing Values in Tuples:
To access values in tuple, use the square brackets for slicing along with the index or
indices to obtain value available at that index.
For example
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0];
print "tup2[1:5]: ", tup2[1:5];
Output:
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
Using Loops to access tuples
You can loop through the list items by using a while loop.
Use the len() function to determine the length of the tuple, then start at 0 and loop your
way through the tuple items by referring to their indexes.
Remember to increase the index by 1 after each iteration.
Using For Loop
Example tup1=(“Orange”,”Apple”,”Grapes”)
thistuple = ("amita", "adesh", "cherry") For x in tup1:
i=0 print(x)
while i < len(thistuple):
Output:
print(thistuple[i]) Orange
i=i+1 Apple
Grapes
Updating Tuples
Tuples are immutable which means you cannot update or change the values of tuple elements. You are able to take
portions of existing tuples to create new tuples.
Example:
tup1 = (112,56);
tup2 = ('red', 'green');
# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print tup3;
Output:
(112,56, 'red', 'green')
Deleting 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.
Example:
Output:
tup = ('physics', 'chemistry', 1997, 2000);
('physics', 'chemistry', 1997, 2000)
print tup;
After deleting tup :
del tup;
Traceback (most recent call last):
print "After deleting tup : ";
File "test.py", line 9, in <module>
print tup;
print tup;
NameError: name 'tup' is not defined
ASSIGNMENT:
1. Write a python program to make use of nested tuples and try to
find sum of all elements within tuple.