Unit 3
Unit 3
Python List
Accessing List
The elements of the list can be accessed by using the slice operator [].
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.
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]
MM Polytechnic,Thergaon Pune
CO: PERFORM OPERATIONS ON DATA STRUCTURES IN PYTHON
print(List)
Output :[1, 2, 3, 4, 5, 6]
List[2] = 10;
print(List)
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.
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:
[1, 2, 3]
MM Polytechnic,Thergaon Pune
CO: PERFORM OPERATIONS ON DATA STRUCTURES IN PYTHON
Python provides the following built-in functions which can be used with the lists.
SN Function Description
The concatenation (+) and repetition (*) operator work in the same way as they were working with the strings.
Repetition The repetition operator enables the list elements to be repeated L1*2 = [1, 2, 3, 4, 1, 2,
multiple times. 3, 4]
Concatenation It concatenates the list mentioned on either side of the operator. l1+l2 = [1, 2, 3, 4, 5, 6,
7, 8]
Membership It returns true if a particular item exists in a particular list print(2 in l1) prints
otherwise false. True.
Iteration The for loop is used to iterate over the list elements. for i in l1:
MM Polytechnic,Thergaon Pune
CO: PERFORM OPERATIONS ON DATA STRUCTURES IN PYTHON
print(i)
Output
1
2
3
4
Python Tuple
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.
3. Tuple can be used as the key inside dictionary due to its immutable nature.
Accessing tuple
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.
MM Polytechnic,Thergaon Pune
CO: PERFORM OPERATIONS ON DATA STRUCTURES IN PYTHON
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
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
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.
Repetition The repetition operator enables the tuple elements to be repeated T1*2 = (1, 2, 3, 4, 5, 1, 2,
multiple times. 3, 4, 5)
MM Polytechnic,Thergaon Pune
CO: PERFORM OPERATIONS ON DATA STRUCTURES IN PYTHON
Concatenation It concatenates the tuple mentioned on either side of the T1+T2 = (1, 2, 3, 4, 5, 6, 7,
operator. 8, 9)
Membership It returns true if a particular item exists in the tuple otherwise print (2 in T1) prints True.
false.
Iteration The for loop is used to iterate over the tuple elements. for i in T1:
print(i)
Output
1
2
3
4
5
SN Function Description
1 cmp(tuple1, It compares two tuples and returns true if tuple1 is greater than tuple2 otherwise
tuple2) false.
MM Polytechnic,Thergaon Pune
CO: PERFORM OPERATIONS ON DATA STRUCTURES IN PYTHON
List VS Tuple
SN List Tuple
1 The literal syntax of list is shown by the []. The literal syntax of the tuple is shown by the ().
3 The List has the variable length. The tuple has the fixed length.
4 The list provides more functionality than tuple. The tuple provides less functionality than the list.
5 The list Is used in the scenario in which we need The tuple is used in the cases where we need to store
to store the simple collections with no the read-only collections i.e., the value of the items can
constraints where the value of the items can be not be changed. It can be used as the key inside the
changed. dictionary.
Python Set
Creating a set
Output:
MM Polytechnic,Thergaon Pune
CO: PERFORM OPERATIONS ON DATA STRUCTURES IN PYTHON
Output:
Output:
1. discard
2. remove
3. pop
discard() method
Python provides discard() method which can be used to remove the items from the set.
MM Polytechnic,Thergaon Pune
CO: PERFORM OPERATIONS ON DATA STRUCTURES IN PYTHON
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'}
remove() method
thisset.remove("banana")
print(thisset)
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.
Note: Sets are unordered, so when using the pop() method, you will not know which item that gets removed.
Example
x = thisset.pop()
print(x)
print(thisset)
output:
apple
{'cherry', 'banana'}
MM Polytechnic,Thergaon Pune
CO: PERFORM OPERATIONS ON DATA STRUCTURES IN PYTHON
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
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.
add() method
update() method.
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'}
MM Polytechnic,Thergaon Pune
CO: PERFORM OPERATIONS ON DATA STRUCTURES IN PYTHON
– 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]))
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).
any() Return True if any element of the set is true. If the set is empty, return False.
enumerate() Return an enumerate object. It contains the index and value of all the items of set as a pair.
MM Polytechnic,Thergaon Pune
CO: PERFORM OPERATIONS ON DATA STRUCTURES IN PYTHON
sorted() Return a new sorted list from elements in the set(does not sort the set itself).
Dictionary
The keys are the immutable python object, i.e., Numbers, string or tuple.
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 {}.
MM Polytechnic,Thergaon Pune
CO: PERFORM OPERATIONS ON DATA STRUCTURES IN PYTHON
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.
# 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'}
Output:
Dictionary Operations
Below is a list of common dictionary operations:
x = {}
MM Polytechnic,Thergaon Pune
CO: PERFORM OPERATIONS ON DATA STRUCTURES IN PYTHON
access an element
x['two']
x.keys()
x.values()
add an entry
x["four"]=4
change an entry
x["one"] = "uno"
delete an entry
del x["four"]
x.clear()
number of items
z = len(x)
MM Polytechnic,Thergaon Pune
CO: PERFORM OPERATIONS ON DATA STRUCTURES IN PYTHON
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
dict2) the first dictionary values are greater than the second
dictionary, otherwise it returns false.
MM Polytechnic,Thergaon Pune