0% found this document useful (0 votes)
13 views

AI Lab 3 Tuples, Dictionary

Uploaded by

jaxala3388
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

AI Lab 3 Tuples, Dictionary

Uploaded by

jaxala3388
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Lab # 3

Tuples, Dictionary, Sets

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)

# tuple of int, float, string


my_data2 = (1, 2.8, "Hello World")
print(my_data2)

# tuple of string and list


my_data3 = ("Book", [1, 2, 3])
print(my_data3)

# tuples inside another tuple


# nested tuple
my_data4 = ((2, 3, 4), (1, 2, "hi"))
print(my_data4)
Output:
('hi', 'hello', 'bye')
(1, 2.8, 'Hello World')
('Book', [1, 2, 3])
((2, 3, 4), (1, 2, 'hi'))
2.2 Empty tuple:
# empty tuple
my_data = ()

2.3 Tuple with only single element:

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.

# a tuple with single data item


my_data = (99,)

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.

3. How to access tuple elements

We use indexes to access the elements of a tuple. Lets take few example to understand the
working.

3.1 Accessing tuple elements using positive indexes

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")

# displaying all elements


print(my_data)

# accessing first element


# prints "hi"
print(my_data[0])

# accessing third element


# prints "bye"
print(my_data[2])
Output:
('hi', 'hello', 'bye')
hi
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.

3.2 Negative indexes in tuples

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.

my_data = (1, 2, "Kevin", 8.9)

# accessing last element


# prints 8.9
print(my_data[-1])

# prints 2
print(my_data[-3])
Output:
8.9
2

3.3 Accessing elements from nested tuples

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.

my_data = (1, "Steve", (11, 22, 33))

# prints 'v'
print(my_data[1][3])

# prints 22
print(my_data[2][1])
Output:
v
22

4. Operations that can be performed on tuple in Python

Lets see the operations that can be performed on the tuples in Python.

4.1 Changing the elements of a tuple


We cannot change the elements of a tuple because elements of tuple are immutable. However
we can change the elements of nested items that are mutable. For example, in the following
code, we are changing the element of the list which is present inside the tuple. List items are
mutable that’s why it is allowed.

my_data = (1, [9, 8, 7], "World")


print(my_data)

# changing the element of the list


# this is valid because list is mutable
my_data[1][2] = 99
print(my_data)

# changing the element of tuple


# This is not valid since tuple elements are immutable
# TypeError: 'tuple' object does not support item assignment
# my_data[0] = 101
# print(my_data)
Output:

(1, [9, 8, 7], 'World')


(1, [9, 8, 99], 'World')

4.2 Delete operation on tuple

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]

# deleting entire tuple is possible


del my_data

# not possible
# error
# because my_data is deleted
# print(my_data)
Output:

(1, 2, 3, 4, 5, 6)

4.3 Slicing operation in tuples

my_data = (11, 22, 33, 44, 55, 66, 77, 88, 99)
print(my_data)

# elements from 3rd to 5th


# prints (33, 44, 55)
print(my_data[2:5])

# elements from start to 4th


# prints (11, 22, 33, 44)
print(my_data[:4])

# elements from 5th to end


# prints (55, 66, 77, 88, 99)
print(my_data[4:])

# elements from 5th to second last


# prints (55, 66, 77, 88)
print(my_data[4:-1])

# displaying entire tuple


print(my_data[:])
Output:

(11, 22, 33, 44, 55, 66, 77, 88, 99)


(33, 44, 55)
(11, 22, 33, 44)
(55, 66, 77, 88, 99)
(55, 66, 77, 88)
(11, 22, 33, 44, 55, 66, 77, 88, 99)

4.4 Membership Test in Tuples

in: Checks whether an element exists in the specified tuple.


not in: Checks whether an element does not exist in the specified tuple.

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:

(11, 22, 33, 44, 55, 66, 77, 88, 99)


True
False
False
True

4.5 Iterating a tuple

# tuple of fruits
my_tuple = ("Apple", "Orange", "Grapes", "Banana")

# iterating over tuple elements


for fruit in my_tuple:
print(fruit)
Output:

Apple
Orange
Grapes
Banana

Basic Tuple operations


The operators like concatenation (+), repetition (*), Membership (in) works in the same way as they work with
the list. Consider the following table for more detail.

Let's say Tuple t = (1, 2, 3, 4, 5) and Tuple t1 = (6, 7, 8, 9) are declared.

Operator Description Example

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

Python Tuple inbuilt functions


S Function Description
N

1 cmp(tuple1, It compares two tuples and returns true if tuple1 is greater than tuple2 otherwise
tuple2) false.

2 len(tuple) It calculates the length of the tuple.

3 max(tuple) It returns the maximum element of the tuple

4 min(tuple) It returns the minimum element of the tuple.

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:

Change values in Dictionary


Here we are updating the values for the existing key-value pairs. To update a value in
dictionary we are using the corresponding key.
mydict = {'StuName': 'Ajeet', 'StuAge': 30, 'StuCity': 'Agra'}
print("Student Age before update is:", mydict['StuAge'])
print("Student City before update is:", mydict['StuCity'])
mydict['StuAge'] = 31
mydict['StuCity'] = 'Noida'
print("Student Age after update is:", mydict['StuAge'])
print("Student City after update is:", mydict['StuCity'])
Output:

Adding a new entry (key-value pair) in dictionary


We can also add a new key-value pair in an existing dictionary. Let’s take an example to
understand this.
mydict = {'StuName': 'Steve', 'StuAge': 4, 'StuCity': 'Agra'}
mydict['StuClass'] = 'Jr.KG'
print("Student Name is:", mydict['StuName'])
print("Student Class is:", mydict['StuClass'])
Output:

Loop through a dictionary


We can loop through a dictionary as shown in the following example. Here we are using for
loop.
mydict = {'StuName': 'Steve', 'StuAge': 4, 'StuCity': 'Agra'}
for e in mydict:
print("Key:",e,"Value:",mydict[e])
Output:

Python delete operation on dictionary


We can delete key-value pairs as well as entire dictionary in python. Let’s take an example.
As you can see we can use del following by dictionary name and in square brackets we can
specify the key to delete the specified key value pair from dictionary.
To delete all the entries (all key-value pairs) from dictionary we can use the clear() method.
To delete entire dictionary along with all the data use del keyword followed by dictionary
name as shown in the following example.
mydict = {'StuName': 'Steve', 'StuAge': 4, 'StuCity': 'Agra'}
del mydict['StuCity']; # remove entry with key 'StuCity'
mydict.clear(); # remove all key-value pairs from mydict
del mydict ; # delete entire dictionary mydict

Built-in Dictionary functions


The built-in python dictionary methods along with the description are given below.
S Function Description
N

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.

2 len(dict) It is used to calculate the length of the dictionary.

3 str(dict) It converts the dictionary into the printable string representation.

4 type(variable It is used to print the type of the passed variable.


)
Built-in Dictionary methods
The built-in python dictionary methods along with the description are given below.
S Method Description
N

1 dic.clear() It is used to delete all the items of the dictionary.

2 dict.copy() It returns a shallow copy of the dictionary.

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")

5 dict.has_key(key) It returns true if the dictionary contains the specified key.

6 dict.items() It returns all the key-value pairs as a tuple.

7 dict.keys() It returns all the keys of the dictionary.

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

9 dict.update(dict2) It updates the dictionary by adding the key-value pair of dict2


to this dictionary.

10 dict.values() It returns all the values of 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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy