Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example −

When the above code is executed, it produces the following result −
dict['Age'] : 8
dict['School'] : DPS School
Delete Dictionary Elements
You can either remove individual dictionary elements or clear the entire contents of a
dictionary. You can also delete the entire dictionary in a single operation. To explicitly remove an entire dictionary, just use the del statement. Following is a simple example −
Accessing Values in Tuples
To access values in a tuple, use the square brackets for slicing along with the index or
indices to obtain the value available at that index. For example −
tup1[0] : physics
tup2[1:5] : [2, 3, 4, 5]
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 as the
following example demonstrates −
When the above code is executed, it produces the following result −
(12, 34.56, 'abc&', 'xyz')
Delete 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. For example −
To explicitly remove an entire tuple, just use the del statement. For example −
This produces the following result. Note an exception raised, this is because after del
tup tuple does not exist anymore −
('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
Accessing Values in Lists
To access values in lists, use the square brackets for slicing along with the index or
indices to obtain value available at that index. For example −
When the above code is executed, it produces the following result −
list1[0] : physics
list2[1:5] : [2, 3, 4, 5]
Updating Lists
You can update single or multiple elements of lists by giving the slice on the left-hand
side of the assignment operator, and you can add to elements in a list with the
append() method. For example −
Note − append() method is discussed in subsequent section.
When the above code is executed, it produces the following result −
Value available at index 2 :
1997
New value available at index 2 :
2001
Delete List Elements
To remove a list element, you can use either the del statement if you know exactly
which element(s) you are deleting or the remove() method if you do not know. For
example −
When the above code is executed, it produces the following result −
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]
Note − remove() method is discussed in a subsequent section.







Comments
Post a Comment
Please, do not enter any spam link in the comment box.