Unit 3 Python PSG
Unit 3 Python PSG
Gaidhani
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.
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)
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:
Mrs. P.S.Gaidhani
[1, 2, 3]
Mrs. P.S.Gaidhani
Python provides the following built-in functions which can be used with the lists.
SN Function Description
descending Order:
my_list = [3, 1, 4, 2]
my_list.sort(reverse=True)
print(my_list) # Output: [1, 2, 3, 4]
1
2
3
4
Length It is used to get the length of the list Len(l1)=4
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.
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
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.
Mrs. P.S.Gaidhani
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
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]
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
Creating a set
Output:
Output:
{'Friday', 'Wednesday', 'Thursday', 'Saturday', 'Monday', 'Tuesday', 'Sunday'}
Output:
Mrs. P.S.Gaidhani
a. discard
b. remove
c. pop
1.discard() method
Python provides discard() method which can be used to remove the items from the set.
output:
{'February', 'January', 'March', 'April', 'June', 'May'}
Removing some months from the set...
2. remove() method
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.
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'}
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.
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'}
| 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]))
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.
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
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:
x = {}
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
Mrs. P.S.Gaidhani
z = len(x)
Mrs. P.S.Gaidhani
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.