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

Assignment 3 Utkarsh

The document discusses a Python assignment on tuple, set and dictionary datatypes. It contains questions and answers related to the characteristics and methods of these datatypes. Examples are given to demonstrate various methods like count, index, union, update etc.

Uploaded by

bubunkumar84
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Assignment 3 Utkarsh

The document discusses a Python assignment on tuple, set and dictionary datatypes. It contains questions and answers related to the characteristics and methods of these datatypes. Examples are given to demonstrate various methods like count, index, union, update etc.

Uploaded by

bubunkumar84
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Assignment 3 : Tuple, Set & Dict - Utkarsh Gaikwad

Assignment 3 pdf Link

Question 1

Question 1 : What are the characteristics of the tuples? Is tuple


immutable?

Answer :
The main characteristics of a tuple in Python are:

1. Immutable: Once a tuple is created, its elements cannot be changed or modified.


2. Ordered: The elements in a tuple have a defined order, and this order is maintained.
3. Heterogeneous: Tuples can store elements of different data types.
4. Indexed: Each element in a tuple can be retrieved by using its index number.
5. Uses parentheses: Tuples are defined using parentheses, like this: (1, 2, 3).
6. In summary, tuples are ordered, heterogeneous, and immutable collections of elements that can be indexed.

Question 2

Question 2: What are the two tuple methods in python? Give an example
of each method. Give a reason why tuples have only two in-built methods
as compared to Lists

Answer - Two Functionalities in tuples are :


1. count() - returns the number of occurrences of a given element in the tuple.
2. index() - returns the index of the first occurrence of a given element in the tuple.

In [3]:
#Example of count functionlaity
t = (1,3,3,3,3,4,4,4,4,5,5,6,1)
print('Count of element 1 in tuple is',t.count(1))
print('Count of element 2 in tuple is',t.count(2))
print('Count of element 3 in tuple is',t.count(3))
print('Count of element 4 in tuple is',t.count(4))
Count of element 1 in tuple is 2
Count of element 2 in tuple is 0
Count of element 3 in tuple is 4
Count of element 4 in tuple is 4

In [5]:
#Example of index functionality
t = (1,3,3,3,3,4,4,4,4,5,5,6,1)
t.index(4)
Out[5]:
5

Tuples have only two in-built methods because they are meant to be lightweight, immutable collections of
elements. The idea is to keep them simple, fast, and efficient, rather than providing a lot of functionalities like
lists. The two methods provided are the most commonly used ones for tuples. In other cases, it is
recommended to use other data structures like lists or dictionaries.

Question 3

Question 3 : Which collection datatypes in python do not allow duplicate


items? Write a code using a set to remove duplicates from the given
list.
List = [1, 1, 1, 2, 1, 3, 1, 4, 2, 1, 2, 2, 2, 3, 2, 4, 3, 1, 3, 2, 3, 3, 3, 4, 4, 1, 4, 2, 4, 3, 4, 4]

Answer : The datatype 'Set' does not allow the duplication of items
In [10]:
lst = [1, 1, 1, 2, 1, 3, 1, 4, 2, 1, 2, 2, 2, 3, 2, 4, 3, 1, 3, 2, 3, 3, 3, 4, 4, 1, 4,
2, 4, 3, 4, 4]
lst1 = set(lst) #Typecasting to set to remove duplicates
lst1 = list(lst1) #Typecasting back to list
print(lst1)

[1, 2, 3, 4]

Question 4

Question 4 - Explain the difference between the union() and update()


methods for a set. Give an example of each method.

Answer
Both union() and update() are methods for set objects in Python. They are used to combine the elements of two
or more sets. However, they have some differences in their implementation and usage:

1. union(): Returns a set that contains all elements from the original set and all elements from one or more
other sets
2. update(): Adds all elements from one or more other sets to the original set.

In summary, the union() method returns a new set that contains the union of two or more sets, while the update()
method updates the original set to contain the union of itself and one or more other sets.

In [12]:
# Union Example
s1 = {'cat','dog','otter','horse'}
s2 = {'horse','cat','donkey','monkey'}
s1.union(s2) # This output will give an entire new set which can be stored into a variabl
e
Out[12]:
{'cat', 'dog', 'donkey', 'horse', 'monkey', 'otter'}

In [13]:
# Update example
s1 = {'cat','dog','otter','horse'}
s2 = {'horse','cat','donkey','monkey'}
s1.update(s2)

In [14]:
s1
Out[14]:

{'cat', 'dog', 'donkey', 'horse', 'monkey', 'otter'}

In [15]:
s2
Out[15]:
{'cat', 'donkey', 'horse', 'monkey'}

Question 5

Question 5 : What is a dictionary? Give an example. Also, state whether a


dictionary is ordered or unordered

Answer:
A dictionary in Python is an unordered collection of key-value pairs, where each key is unique.\ It is an
implementation of a hash table data structure, and it is often used to store and retrieve data efficiently.

In [18]:
#Example of Dictionary
dct = {'name':'Utkarsh Gaikwad','gender':'male','hobby':'music','favourite subject':'calc
ulus'}
print(dct)
print(type(dct))

{'name': 'Utkarsh Gaikwad', 'gender': 'male', 'hobby': 'music', 'favourite subject': 'cal
culus'}
<class 'dict'>

Dictionaries in Python are unordered, which means that the elements are not stored in a particular order, and
their order may change over time.\ The order of the elements can be controlled by sorting the keys, but by
default, the order is not guaranteed.

Question 6

Question 6 : Can we create a nested dictionary? If so, please give an


example by creating a simple one-level nested dictionary.

Answer : Yes we can create a nested dictionary in Python


In [21]:
nest_dct = {'apple':{'color':'red','type':'fruit'},'spinach':{'color':'green','type':'le
afy vegetable'}}
nest_dct
Out[21]:
{'apple': {'color': 'red', 'type': 'fruit'},
'spinach': {'color': 'green', 'type': 'leafy vegetable'}}

Question 7

Question 7 : Using setdefault() method, create key named topics in the


given dictionary and also add the value of the key as this list ['Python',
'Machine Learning’, 'Deep Learning']

dict1 = {'language' : 'Python', 'course': 'Data Science Masters'}

Answer :
In [23]:
dict1 = {'language' : 'Python', 'course': 'Data Science Masters'}
dict1.setdefault('topics', ['Python', 'Machine Learning', 'Deep Learning'])
dict1
Out[23]:
{'language': 'Python',
'course': 'Data Science Masters',
'topics': ['Python', 'Machine Learning', 'Deep Learning']}
'topics': ['Python', 'Machine Learning', 'Deep Learning']}

Question 8

Question 8 : What are the three view objects in dictionaries? Use the
three in-built methods in python to display these three view objects for
the given dictionary.

dict1 = {'Sport': 'Cricket' , 'Teams': ['India', 'Australia', 'England', 'South Africa', 'Sri Lanka',
'New Zealand']}

Answer
In [24]:
dict1 = {'Sport': 'Cricket' , 'Teams': ['India', 'Australia', 'England', 'South Africa',
'Sri Lanka', 'New Zealand']}

In [25]:
dir(dict1)
Out[25]:
['__class__',
'__class_getitem__',
'__contains__',
'__delattr__',
'__delitem__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__ior__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__ne__',
'__new__',
'__or__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__reversed__',
'__ror__',
'__setattr__',
'__setitem__',
'__sizeof__',
'__str__',
'__subclasshook__',
'clear',
'copy',
'fromkeys',
'fromkeys',
'get',
'items',
'keys',
'pop',
'popitem',
'setdefault',
'update',
'values']

Example 1 : get()
get(key[, default]) \ Return the value for key if key is in the dictionary, else default. If default is not given, it
defaults to None, so that this method never raises a KeyError.

In [30]:
dict1.get('Sport')
Out[30]:
'Cricket'

In [31]:
print(dict1.get('name'))

None

Example 2: reversed()
Return a reverse iterator over the keys of the dictionary.

In [33]:
print(reversed(dict1))

<dict_reversekeyiterator object at 0x00000123B069CE00>

In [34]:
for i in reversed(dict1):
print(i)

Teams
Sport

In [35]:
for i in dict1:
print(i)

Sport
Teams

Example 3: keys()
Return a new view of the dictionary’s keys.

In [36]:
dict1.keys()
Out[36]:
dict_keys(['Sport', 'Teams'])

You might also like