Mrs. P.S.
Gaidhani
UNIT 3: DATA STRUCTURES IN PYTHON
Q. Define List with Example
Python List
• List in python is implemented to store the sequence of various type of data
• A list can be defined as a collection of values or items of different types.
• The items in the list are separated with the comma (,) and enclosed with the square brackets [].
A list can be defined as follows.
1. L1 = ["MMP", 102, "USA"]
2. L2 = [1, 2, 3, 4, 5, 6]
3. L3 = [1, "GAD"]
Accessing List
• The elements of the list can be accessed by using the sliceoperator []. The index starts from 0 and goes to length - 1.
• The first element of the list is stored at the 0th index, the second element of the list is stored at the 1st index, and so
on.
Consider the following example.
Mrs. P.S.Gaidhani
Q. How to update the values of List ?
Updating List values
Lists are the most versatile data structures in python since they are immutable and their values can be updated by
using the slice and assignment operator.
List = [1, 2, 3, 4, 5, 6]
print(List)
Output :[1, 2, 3, 4, 5, 6]
List[2] = 10;
print(List)
Output: [1, 2, 10, 4, 5, 6]
List[1:3] = [89, 78]
print(List)
Output : [1, 89, 78, 4, 5, 6]
Q. How to delete values of List
Deleting List values
The list elements can also be deleted by using the del keyword. Python also provides us the remove() method if we
do not know which element is to be deleted from the list.
Consider the following example to delete the list elements.
List = [0,1,2,3,4]
print(List)
Output:
[0, 1, 2, 3, 4]
del List[0]
print(List)
Output:
[1, 2, 3, 4]
del List[3]
print(List)
Output:
Mrs. P.S.Gaidhani
[1, 2, 3]
Mrs. P.S.Gaidhani
Q. List and Explain Python List Built-in functions
Python provides the following built-in functions which can be used with the lists.
SN Function Description
1 append() Adds an element to the end of the list.
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
2 extend() Extends the list by appending elements from another iterable.
my_list = [1, 2, 3]
my_list.extend([4, 5, 6])
print(my_list) # Output: [1, 2, 3, 4, 5, 6]
3 insert() Inserts an element at the specified position.
my_list = [1, 2, 4]
my_list.insert(2, 3)
print(my_list) # Output: [1, 2, 3, 4]
4 remove() Removes the first occurrence of a value from the list.
my_list = [1, 2, 3, 4]
my_list.remove(3)
print(my_list) # Output: [1, 2, 4]
5 pop() Removes and returns the element at the specified position.
my_list = [1, 2, 3, 4]
popped_element = my_list.pop(1)
print(popped_element) # Output: 2
print(my_list) # Output: [1, 3, 4]
6 clear() Removes all elements from the list.
pythonmy_list = [1, 2, 3, 4]
my_list.clear()
print(my_list) # Output: []
7 index() Returns the index of the first occurrence of a value
my_list = [1, 2, 3, 4]
index = my_list.index(3)
print(index) # Output: 2
8 count() Returns the number of occurrences of a value in the list.
my_list = [1, 2, 2, 3, 3, 3, 4]
count = my_list.count(3)
print(count) # Output: 3
9 reverse() reverse(): Reverses the elements of the list in place.
my_list = [1, 2, 3, 4]
my_list.reverse()
print(my_list) # Output: [4, 3, 2, 1]
Mrs. P.S.Gaidhani
10 sort() sort(): Sorts the elements of the list in place.
my_list = [3, 1, 4, 2]
my_list.sort()
print(my_list) # Output: [1, 2, 3, 4]
descending Order:
my_list = [3, 1, 4, 2]
my_list.sort(reverse=True)
print(my_list) # Output: [1, 2, 3, 4]
11 len(list) It is used to calculate the length of the list.
my_list = [10, 20, 30, 40, 50]
print(len(my_list)) # Output: 5
12 max(list) It returns the maximum element of the list.
my_list = [10, 20, 30, 40, 50]
print(max(my_list)) # Output: 50
13 min(list) It returns the minimum element of the list.
my_list = [10, 20, 30, 40, 50]
print(min(my_list)) # Output: 10
Converts a sequence (e.g., tuple, string) into a list.
14 list(seq) my_tuple = (1, 2, 3)
converted_list = list(my_tuple)
print(converted_list) # Output: [1, 2, 3]
Q .List and Explain Python List Operations
The concatenation (+) and repetition (*) operator work in the same way as they were working with the strings.
Consider a List l1 = [1, 2, 3, 4] and l2 = [5, 6, 7, 8]
Operator Description Example
The repetition operator enables the list
Repetition elements to be repeated multiple times. L1*2 = [1, 2, 3, 4, 1, 2,3, 4]
It concatenates the list mentioned on
Concatenation either side of the operator. l1+l2 = [1, 2, 3, 4, 5, 6,7, 8]
It returns true if a particular item exists
Membership in a particular list otherwise false. print(2 in l1) prints True.
The for loop is used to iterate over the
Iteration list elements. for i in l1:
print(i)
Output
Mrs. P.S.Gaidhani
1
2
3
4
Length It is used to get the length of the list Len(l1)=4
Q. Define Python Tuple with Example
Python Tuple
• Python Tuple is used to store the sequence of immutable python objects.
• Tuple is immutable and the value of the items stored in the tuple cannot be changed.
• A tuple can be written as the collection of comma-separated values enclosed with the small
brackets.
Where use tuple
Using tuple instead of list is used in the following scenario.
1. Using tuple instead of list gives us a clear idea that tuple data is constant and must not be changed.
2. Tuple can simulate dictionary without keys. Consider the following nested structure which
can be used as a dictionary.
[(101, "CO", 22), (102, "ME", 28), (103, "AE", 30)]
3. Tuple can be used as the key inside dictionary due to its immutable nature.
A tuple can be defined as follows.
T1 = (101, "Ayush", 22)
T2 = ("Apple", "Banana", "Orange")
Q. How to Access tuple
Accessing tuple
The indexing in the tuple starts from 0 and goes to length(tuple) - 1.
The items in the tuple can be accessed by using the slice operator. Python also allows us to use
the colon operator to access multiple items in the tuple.
Mrs. P.S.Gaidhani
The tuple items can not be deleted by using the del keyword as tuples are immutable. To delete
an entire tuple, we can use the del keyword with the tuple name
Consider the following example.
tuple1 = (1, 2, 3, 4, 5, 6)
print(tuple1)
del tuple1
print(tuple1)
Output:
(1, 2, 3, 4, 5, 6)
Traceback (most recent call
last): File "tuple.py", line 4,
in <module> print(tuple1)
NameError: name 'tuple1' is not defined
Q. List and Explain 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.
Mrs. P.S.Gaidhani
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 T1*2 = (1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
elements to be repeated multiple times.
Concatenatio It concatenates the tuple mentioned on either T1+T2 = (1, 2, 3, 4, 5, 6, 7,8, 9)
n side of the operator.
Membership It returns true if a particular item exists in the print (2 in T1) prints True.
tuple otherwise false.
Iteration The for loop is used to iterate over the tuple for i in T1: print(i)
elements. Output
1
2
3
4
5
Length It is used to get the length of the tuple. len(T1) = 5
Q. List and Explain Python Tuple inbuilt functions
1.len(): Returns the number of elements in a tuple.
my_tuple = (1, 2, 3, 4, 5)
print(len(my_tuple)) # Output: 5
2.min(): Returns the smallest element in a tuple.
my_tuple = (10, 20, 30, 40, 50)
print(min(my_tuple)) # Output: 10
Mrs. P.S.Gaidhani
3. max(): Returns the largest element in a tuple.
my_tuple = (10, 20, 30, 40, 50)
print(max(my_tuple)) # Output: 50
4. sum(): Returns the sum of all elements in a tuple.
my_tuple = (1, 2, 3, 4, 5)
print(sum(my_tuple)) # Output: 15
5. sorted(): Returns a new sorted list from the elements of the tuple.
my_tuple = (3, 1, 4, 1, 5, 9, 2, 6)
sorted_list = sorted(my_tuple)
print(sorted_list) # Output: [1, 1, 2, 3, 4, 5, 6, 9]
6. tuple(seq): Converts a sequence (e.g., list, string) into a tuple.
my_list = [1, 2, 3]
converted_tuple = tuple(my_list)
print(converted_tuple) # Output: (1, 2, 3)
Mrs. P.S.Gaidhani
List VS Tuple
S List Tuple
N
The literal syntax of list is shown by the The literal syntax of the tuple is shown by the
1 []. ().
Lists are mutable, meaning you can Tuples are immutable, meaning once they are
2 change, add, or remove elements after created, their elements cannot be changed,
the list is created. added, or removed.
The List has the variable length. The tuple has the fixed length.
3
The list provides more functionality than The tuple provides less functionality than the
4 tuple. list.
The list Is used in the scenario in The tuple is used in the cases where we need
5 which we need to store the simple to store the read-only collections i.e., the
collections with no constraints where value of the items can not be changed. It can
the value of the items can be changed. be used as the key inside the dictionary.
6 # List example # Tuple example
my_list = [1, 2, 3] my_tuple = (1, 2, 3)
my_list.append(4) # Attempting to modify a tuple will raise an error
print(my_list) # Output: [1, 2, 3, 4] # my_tuple.append(4) # This would raise an
AttributeError
print(my_tuple) # Output: (1, 2, 3)
Mrs. P.S.Gaidhani
Q. Define Set in Python
Python Set
Unordered collection of various items enclosed within the
curly braces. The elements of the set can not be duplicate.
The elements of the python set must be immutable.
Creating a set
Example 1: using curly braces
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
print(Days)
print(type(Days))
Output:
{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday', 'Wednesday'}
<class 'set'>
Example 2: using set() method
Days = set (["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"])
print(Days)
Output:
{'Friday', 'Wednesday', 'Thursday', 'Saturday', 'Monday', 'Tuesday', 'Sunday'}
Accessing set values
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
print(Days)
print("the set elements ... ")
for i in Days:
print(i)
Output:
Mrs. P.S.Gaidhani
{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday',
'Wednesday'} the set elements ...
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesd
Q.
ay How to remove items from set
Removing items from the set
Following methods used to remove the items from the set
a. discard
b. remove
c. pop
1.discard() method
Python provides discard() method which can be used to remove the items from the set.
Months = set(["January","February", "March", "April", "May", "June"])
print("\nRemoving some months from the set...");
Months.discard("January");
Months.discard("May");
print("\nPrinting the modified set...");
print(Months)
output:
{'February', 'January', 'March', 'April', 'June', 'May'}
Removing some months from the set...
Printing the modified set...
{'February', 'March', 'April', 'June'}
2. remove() method
Remove "banana" by using the remove() method:
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
Mrs. P.S.Gaidhani
output:
{"apple”, "cherry"}
pop() method
the pop(), method to remove an item, but this method will remove the last item.
Remember that sets are unordered, so you will not know what item that gets removed.
The return value of the pop() method is the removed item.
Note: Sets are unordered, so when using the pop() method, you will not know which item that gets
removed.
Example
Remove the last item by using the pop() method:
thisset = {"apple", "banana", "cherry"}
x=thisset.pop()
print(x)
print(thisset)
output:
apple
{'cherry', 'banana'}
Q. How to delete set in Python
delete the set
The del keyword will delete the set completely:
thisset = {"apple", "banana",
"cherry"} del thisset
print(thisset)
output:
File "demo_set_del.py", line 5, in <module>
print(thisset) #this will raise an error because the set no
longer exists NameError: name 'thisset' is not defined
Difference between discard() and remove()
Mrs. P.S.Gaidhani
• If the key to be deleted from the set using discard() doesn't exist in the set, the python will
not give the error. The program maintains its control flow.
• On the other hand, if the item to be deleted from the set using remove() doesn't exist in
the set, the python will give the error.
Q. How to add items in set
Adding items to the set
• add() method
• update() method.
add()
Python provides the add() method which can be used to add some particular item to the
set. Months = set(["January","February", "March", "April", "May", "June"])
Months.add("July");
Months.add("August");
print(Months)
output:
{'February', 'July', 'May', 'April', 'March', 'August', 'June', 'January'}
update([])
Months = set(["January","February", "March", "April", "May", "June"])
Months.update(["July","August","September","October"]);
print(Months)
output:
{'January', 'February', 'April', 'August', 'October', 'May', 'June', 'July', 'September', 'March'}
Python set operations (union, intersection, difference and symmetric difference)
In Python, below quick operands can be used for different operations.
Mrs. P.S.Gaidhani
| for union.
& for intersection.
– for difference
^ for symmetric difference
A = {0, 2, 4, 6, 8};
B = {1, 2, 3, 4, 5};
# union
print("Union :", A | B)
# intersection
print("Intersection :", A &
B)
# difference
print("Difference :", A -
B)
# symmetric difference
print("Symmetric difference :",
A ^B)
Output:
('Union :', set([0, 1, 2, 3, 4, 5, 6, 8]))
('Intersection :', set([2, 4]))
('Difference :', set([8, 0, 6]))
('Symmetric difference :', set([0, 1, 3, 5, 6, 8]))
Q. Explain Built-in Functions with Set
Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc. are commonly used with set
to perform different tasks.
Function Description
all() Return True if all elements of the set are true (or if the set is empty).
my_set = {True, True, False, True}
print(all(my_set)) # Output: False
Mrs. P.S.Gaidhani
another_set = {1, 2, 3, 4}
print(all(another_set)) # Output: True
any() Return True if any element of the set is true. If the set is empty, return False.
my_set = {False, False, True, False}
print(any(my_set)) # Output: True
another_set = {0, 0, 0, 0}
print(any(another_set)) # Output: False
enumerate() Return an enumerate object. It contains the index and value of all the items of set as a
pair.
# Define a list of fruits
fruits = ["apple", "banana", "orange", "grape"]
# Use enumerate to iterate over the list
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
# Another example: Using enumerate with a starting index
for i, fruit in enumerate(fruits, start=1):
print(f"Fruit {i}: {fruit}")
len() Return the length (the number of items) in the set.
my_set = {10, 20, 30, 40, 50}
set_length = len(my_set)
print("Length of the set:", set_length) # Output: Length of the set: 5
max() Return the largest item in the set.
my_set = {10, 20, 30, 40, 50}
maximum_element = max(my_set)
print("Maximum element in the set:", maximum_element)
Mrs. P.S.Gaidhani
min() Return the smallest item in the set.
my_set = {10, 20, 30, 40, 50}
minimum_element = min(my_set)
print("Minimum element in the set:", minimum_element)
sorted() Return a new sorted list from elements in the set(does not sort the set itself).
my_set = {5, 3, 8, 2, 1, 9}
sorted_set_desc = sorted(my_set, reverse=True)
print("Sorted set in descending order:", sorted_set_desc)
sum() Return the sum of all elements in the set.
my_set = {1, 2, 3, 4, 5}
sum_of_set = sum(my_set)
print("Sum of the set:", sum_of_set)
Q. Define dictionary in Python
Dictionary
Dictionary is used to implement the key-value pair in python.
The keys are the immutable python object, i.e., Numbers, string or tuple.
Q. How to creare Dictionay and Access dictionary in python
Creating the dictionary
The dictionary can be created by using multiple key-value pairs enclosed with the small brackets () and separated
by the colon (:).
The collections of the key-value pairs are enclosed within the curly braces
{}. The syntax to define the dictionary is given below.
Dict = {"Name": "Ayush","Age": 22}
Accessing the dictionary values
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(Employee
) output:
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}
The dictionary values can be accessed in the following way:
Mrs. P.S.Gaidhani
Employee = {"Name": "John", "Age": 29,
"salary":25000,"Company":"GOOGLE"} print("printing Employee data")
print("Name :",Employee["Name"])
print("Age : ",Employee["Age"])
print("Salary : ",Employee["salary"])
print("Company : ",
Employee["Company"])
Q. How to update and delete dictionary values
Updating dictionary values
Dictionary is mutable. We can add new items or change the value of existing items using assignment operator. If
the key is already present, value gets updated, else a new key: value pair is added to the dictionary.
my_dict = {'name':'MMP', 'age': 26}
# update value
my_dict['age'] = 27
print(my_dict)
Output: {'age': 27, 'name': 'MMP'}
# add item
my_dict['address'] = 'Downtown'
print(my_dict)
Output: {'address': 'Downtown', 'age': 27, 'name': 'MMP'}
Deleting elements using del keyword
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
del Employee["Name"]
del Employee["Company"]
print("printing the modified information ")
print(Employee
) Output:
printing the modified information
{'Age': 29, 'salary': 25000}
Mrs. P.S.Gaidhani
Q. Explain Dictionary Operations
Below is a list of common dictionary operations:
create an empty dictionary
x = {}
create a three items dictionary
x = {"one":1, "two":2, "three":3}
access an element
x['two']
get a list of all the keys
x.keys()
get a list of all the values
x.values()
add an entry
x["four"]=4
change an entry
x["one"] = "uno"
delete an entry
del x["four"]
remove all items
x.clear()
number of items
Mrs. P.S.Gaidhani
z = len(x)
Mrs. P.S.Gaidhani
looping over keys
for item in x.keys(): print item
looping over values
for item in x.values(): print item
Q. Explain Built-in Dictionary functions
The built-in python dictionary methods along with the description are given below.
SN Function Description
1 cmp(dict1, It compares the items of both the dictionary and returns true if the
dict2) first 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.