AI Lab 3 Tuples, Dictionary
AI Lab 3 Tuples, Dictionary
In Python, a tuple is similar to List except that the objects in tuple are immutable which
means we cannot change the elements of a tuple once assigned. On the other hand, we can
change the elements of a list.
1. Tuple vs List
1. The elements of a list are mutable whereas the elements of a tuple are immutable.
2. When we do not want to change the data over time, the tuple is a preferred data type
whereas when we need to change the data in future, list would be a wise option.
3. Iterating over the elements of a tuple is faster compared to iterating over a list.
4. Elements of a tuple are enclosed in parenthesis whereas the elements of list are
enclosed in square bracket.
2. How to create a tuple in Python
To create a tuple in Python, place all the elements in a () parenthesis, separated by commas.
A tuple can have heterogeneous data items, a tuple can have string and list as data items as
well.
2.1 Example – Creating tuple
In this example, we are creating few tuples. We can have tuple of same type of data items as
well as mixed type of data items. This example also shows nested tuple (tuples as data items
in another tuple).
# tuple of strings
my_data = ("hi", "hello", "bye")
print(my_data)
Note: When a tuple has only one element, we must put a comma after the element, otherwise
Python will not treat it as a tuple.
If we do not put comma after 99 in the above example then python will treat my_data as an
int variable rather than a tuple.
We use indexes to access the elements of a tuple. Lets take few example to understand the
working.
We can also have negative indexes in tuple. Indexes starts with 0 that is why we use 0 to
access the first element of tuple, 1 to access second element and so on.
# tuple of strings
my_data = ("hi", "hello", "bye")
Note:
1. 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.
2. 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 occur.
Similar to list and strings we can use negative indexes to access the tuple elements from the
end.
-1 to access last element, -2 to access second last and so on.
# prints 2
print(my_data[-3])
Output:
8.9
2
Lets understand how the double indexes are used to access the elements of nested tuple. The
first index represents the element of main tuple and the second index represent the element of
the nested tuple.
In the following example, when we used my_data[2][1], it accessed the second element of the
nested tuple. Because 2 represented the third element of main tuple which is a tuple and the 1
represented the second element of that tuple.
# prints 'v'
print(my_data[1][3])
# prints 22
print(my_data[2][1])
Output:
v
22
Lets see the operations that can be performed on the tuples in Python.
We already discussed above that tuple elements are immutable which also means that we
cannot delete the elements of a tuple. However deleting entire tuple is possible.
my_data = (1, 2, 3, 4, 5, 6)
print(my_data)
# not possible
# error
# del my_data[2]
# not possible
# error
# because my_data is deleted
# print(my_data)
Output:
(1, 2, 3, 4, 5, 6)
my_data = (11, 22, 33, 44, 55, 66, 77, 88, 99)
print(my_data)
my_data = (11, 22, 33, 44, 55, 66, 77, 88, 99)
print(my_data)
# true
print(22 in my_data)
# false
print(2 in my_data)
# false
print(88 not in my_data)
# true
print(101 not in my_data)
Output:
# tuple of fruits
my_tuple = ("Apple", "Orange", "Grapes", "Banana")
Apple
Orange
Grapes
Banana
Repetition The repetition operator enables the tuple elements to be T*2 = (1, 2, 3, 4, 5, 1, 2,
repeated multiple times. 3, 4, 5)
Concatenatio It concatenates the tuple mentioned on either side of the T1+T2 = (1, 2, 3, 4, 5, 6,
n operator. 7, 8, 9)
Membership It returns true if a particular item exists in the tuple otherwise print (2 in T1) prints
false True.
Iteration The for loop is used to iterate over the tuple elements. for i in T1:
print(i)
Output
1
2
3
4
5
Length It is used to get the length of the tuple. len(T1) = 5
1 cmp(tuple1, It compares two tuples and returns true if tuple1 is greater than tuple2 otherwise
tuple2) false.
Dictionary:
Dictionary is a mutable data type in Python. A python dictionary is a collection of key and
value pairs separated by a colon (:), enclosed in curly braces {}.
Python Dictionary
Here we have a dictionary. Left side of the colon(:) is the key and right side of the : is the
value.
mydict = {'StuName': 'Ajeet', 'StuAge': 30, 'StuCity': 'Agra'}
Points to Note:
1. Keys must be unique in dictionary, duplicate values are allowed.
2. A dictionary is said to be empty if it has no key value pairs. An empty dictionary is
denoted like this: {}
3. The keys of dictionary must be of immutable data types such as String, numbers or tuples.
Accessing dictionary values using keys in Python
To access a value we can use the corresponding key in the square brackets as shown in the
following example. Dictionary name followed by square brackets and in the brackets we
specify the key for which we want the value.
mydict = {'StuName': 'Ajeet', 'StuAge': 30, 'StuCity': 'Agra'}
print("Student Age is:", mydict['StuAge'])
print("Student City is:", mydict['StuCity'])
Output:
If you specify a key which doesn’t exist in the dictionary then you will get a compilation
error. For example. Here we are trying to access the value for key ‘StuClass’ which does not
exist in the dictionary mydict, thus we get a compilation error when we run this code.
mydict = {'StuName': 'Ajeet', 'StuAge': 30, 'StuCity': 'Agra'}
print("Student Age is:", mydict['StuClass'])
print("Student City is:", mydict['StuCity'])
Output:
1 cmp(dict1, It compares the items of both the dictionary and returns true if the first
dict2) dictionary values are greater than the second dictionary, otherwise it returns
false.
3 dict.fromkeys(iterable, value Create a new dictionary from the iterable with the values equal
= None, /) to value.
4 dict.get(key, default = It is used to get the value specified for the passed key.
"None")
8 dict.setdefault(key,default= It is used to set the key to the default value if the key is not
"None") specified in the dictionary
11 len()
12 popItem()
13 pop()
14 count()
15 index()
Lab Tasks
1. Write a python program to declare a tuple with five values, print that tuple and then
reverse the tuple and print again.
2. Write a python program to declare a tuple with 6 values, print those values using loop
3. Write a python program to add a number in a tuple
4. Write a python program to print fourth element of a tuple
5. Write a python program to check whether a specific number exists in tuple or not
6. Write a python program to find length of a tuple
7. Write a python program to merge two python dictionaries into one
8. Write a python program to delete keys from dictionary
9. Write a python program to check whether a certain number exists in dictionary or not
10. Write a python program to rename the key of dictionary
11. Write a python program to merge two dictionaries