In this Python tutorial, let us know about accessing values in tuples, updating tuples or remove elements in a Python tuple using the Python script with suitable examples.
Introduction of Python tuples
A tuple is a sequence of immutable Python objects 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.
tup1 = ('physics', 'chemistry', 1997, 2000); tup2 = (1, 2, 3, 4, 5 ); tup3 = "a", "b", "c", "d";
An empty tuple is written as the following,
tup1 = ();
A tuple containing a single value,
tup1 = (50,);
Accessing Values in Tuples
Use the square brackets for slicing along with the index to obtain value available to access the values in tuples.
Example code to access values
#!/usr/bin/python tup1 = ('physics', 'chemistry', 1997, 2000); tup2 = (1, 2, 3, 4, 5, 6, 7 ); print "tup1: ", tup1; print "tup2[1:5]: ", tup2[1:5];
tup1: physics tup2[1:5]: [2, 3, 4, 5]
Updating the Tuples
We can take portions of existing tuples to create new tuples as like the following,
Example code to update the tuples
#!/usr/bin/python tup1 = (12, 34.56); tup2 = ('abc', 'xyz'); # Following action is not valid for tuples # tup1 = 100; # So let's create a new tuple as follows tup3 = tup1 + tup2; print tup3;
(12, 34.56, 'abc', 'xyz')
Delete Elements in Tuple
To remove an entire tuple use the del statement.
Example code to delete elements in tuple
#!/usr/bin/python tup = ('physics', 'chemistry', 1997, 2000); print tup; del tup; print "After deleting tup : "; print tup;
('physics', 'chemistry', 1997, 2000) After deleting tup : Traceback (most recent call last): File "test.py", line 9, in <module> print tup; NameError: name 'tup' is not defined