0% found this document useful (0 votes)
40 views69 pages

Unit 3

Uploaded by

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

Unit 3

Uploaded by

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

Unit 3

Mutable and immutable

Python List
In Python, the sequence of various data types is stored in a list. A list is a
collection of different kinds of values or items. Since Python lists are mutable,
we can change their elements after forming. The comma (,) and the square
brackets [enclose the List's items] serve as separators.

Although six Python data types can hold sequences, the List is the most
common and reliable form. A list, a type of sequence data, is used to store the
collection of data. Tuples and Strings are two similar data formats for
sequences.

Lists written in Python are identical to dynamically scaled arrays defined in


other languages, such as Array List in Java and Vector in C++. A list is a
collection of items separated by commas and denoted by the symbol [].

List Declaration

Code

1. # a simple list
2. list1 = [1, 2, "Python", "Program", 15.9]
3. list2 = ["Amy", "Ryan", "Henry", "Emma"]
4.
5. # printing the list
6. print(list1)
7. print(list2)
8.
9. # printing the type of list
10.print(type(list1))
11.print(type(list2))
Output:

[1, 2, 'Python', 'Program', 15.9]


['Amy', 'Ryan', 'Henry', 'Emma']
< class ' list ' >
< class ' list ' >

Characteristics of Lists

The characteristics of the List are as follows:

o The lists are in order.


o The list element can be accessed via the index.
o The mutable type of List is
o The rundowns are changeable sorts.
o The number of various elements can be stored in a list.

Ordered List Checking

Code

1. # example
2. a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6 ]
3. b = [ 1, 2, 5, "Ram", 3.50, "Rahul", 6 ]
4. a == b
Output:

False
The indistinguishable components were remembered for the two records;
however, the subsequent rundown changed the file position of the fifth
component, which is against the rundowns' planned request. False is returned
when the two lists are compared.

Code

1. # example
2. a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]
3. b = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]
4. a == b
Output:

True

Records forever protect the component's structure. Because of this, it is an


arranged collection of things.

Let's take a closer look at the list example.

Code

1. # list example in detail


2. emp = [ "John", 102, "USA"]
3. Dep1 = [ "CS",10]
4. Dep2 = [ "IT",11]
5. HOD_CS = [ 10,"Mr. Holding"]
6. HOD_IT = [11, "Mr. Bewon"]
7. print("printing employee data ...")
8. print(" Name : %s, ID: %d, Country: %s" %(emp[0], emp[1], emp[2]))
9. print("printing departments ...")
10.print("Department 1:\nName: %s, ID: %d\n Department 2:\n Name: %s, ID:
%s"%( Dep1[0], Dep2[1], Dep2[0], Dep2[1]))
11.print("HOD Details ....")
12.print("CS HOD Name: %s, Id: %d" %(HOD_CS[1], HOD_CS[0]))
13.print("IT HOD Name: %s, Id: %d" %(HOD_IT[1], HOD_IT[0]))
14.print(type(emp), type(Dep1), type(Dep2), type(HOD_CS), type(HOD_IT))

Output:
printing employee data...
Name : John, ID: 102, Country: USA
printing departments...
Department 1:
Name: CS, ID: 11
Department 2:
Name: IT, ID: 11
HOD Details ....
CS HOD Name: Mr. Holding, Id: 10
IT HOD Name: Mr. Bewon, Id: 11
<class ' list '> <class ' list '> <class ' list '> <class ' list '> <class ' list '>

In the preceding illustration, we printed the employee and department-specific


details from lists that we had created. To better comprehend the List's concept,
look at the code above.

List Indexing and Splitting

The indexing procedure is carried out similarly to string processing. The slice
operator [] can be used to get to the List's components.

The index ranges from 0 to length -1. The 0th index is where the List's first
element is stored; the 1st index is where the second element is stored, and so
on.
We can get the sub-list of the list using the following syntax.

1. list_varible(start:stop:step)

o The beginning indicates the beginning record position of the rundown.


o The stop signifies the last record position of the rundown.
o Within a start, the step is used to skip the nth element: stop.
The start parameter is the initial index, the step is the ending index, and the
value of the end parameter is the number of elements that are "stepped"
through. The default value for the step is one without a specific value. Inside
the resultant Sub List, the same with record start would be available, yet the
one with the file finish will not. The first element in a list appears to have an
index of zero.

Consider the following example:

Code

1. list = [1,2,3,4,5,6,7]
2. print(list[0])
3. print(list[1])
4. print(list[2])
5. print(list[3])
6. # Slicing the elements
7. print(list[0:6])
8. # By default, the index value is 0 so its starts from the 0th element and go for
index -1.
9. print(list[:])
10.print(list[2:5])
11.print(list[1:6:2])
Output:

1
2
3
4
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5]
[2, 4, 6]

In contrast to other programming languages, Python lets you use negative


indexing as well. The negative indices are counted from the right. The index -
1 represents the final element on the List's right side, followed by the index -
2 for the next member on the left, and so on, until the last element on the left
is reached.

Let's have a look at the following example where we will use negative
indexing to access the elements of the list.

Code

1. # negative indexing example


2. list = [1,2,3,4,5]
3. print(list[-1])
4. print(list[-3:])
5. print(list[:-1])
6. print(list[-3:-1])
Output:

5
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]

Negative indexing allows us to obtain an element, as previously mentioned.


The rightmost item in the List was returned by the first print statement in the
code above. The second print statement returned the sub-list, and so on.

Updating List Values

Due to their mutability and the slice and assignment operator's ability to
update their values, lists are Python's most adaptable data structure. Python's
append() and insert() methods can also add values to a list.

Consider the following example to update the values inside the List.

Code

1. # updating list values


2. list = [1, 2, 3, 4, 5, 6]
3. print(list)
4. # It will assign value to the value to the second index
5. list[2] = 10
6. print(list)
7. # Adding multiple-element
8. list[1:3] = [89, 78]
9. print(list)
10.# It will add value at the end of the list
11.list[-1] = 25
12.print(list)
Output:

[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
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.

Code

1. list = [1, 2, 3, 4, 5, 6]
2. print(list)
3. # It will assign value to the value to second index
4. list[2] = 10
5. print(list)
6. # Adding multiple element
7. list[1:3] = [89, 78]
8. print(list)
9. # It will add value at the end of the list
10.list[-1] = 25
11.print(list)
Output:

[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]

Python List Operations

The concatenation (+) and repetition (*) operators work in the same way as
they were working with the strings. The different operations of list are

1. Repetition
2. Concatenation
3. Length
4. Iteration
5. Membership

Let's see how the list responds to various operators.

1. Repetition
The redundancy administrator empowers the rundown components to be
rehashed on different occasions.

Code

1. # repetition of list
2. # declaring the list
3. list1 = [12, 14, 16, 18, 20]
4. # repetition operator *
5. l = list1 * 2
6. print(l)
Output:

[12, 14, 16, 18, 20, 12, 14, 16, 18, 20]

2. Concatenation

It concatenates the list mentioned on either side of the operator.

Code

1. # concatenation of two lists


2. # declaring the lists
3. list1 = [12, 14, 16, 18, 20]
4. list2 = [9, 10, 32, 54, 86]
5. # concatenation operator +
6. l = list1 + list2
7. print(l)
Output:

[12, 14, 16, 18, 20, 9, 10, 32, 54, 86]

3. Length

It is used to get the length of the list

Code

1. # size of the list


2. # declaring the list
3. list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40]
4. # finding length of the list
5. len(list1)
Output:

4. Iteration

The for loop is used to iterate over the list elements.

Code

1. # iteration of the list


2. # declaring the list
3. list1 = [12, 14, 16, 39, 40]
4. # iterating
5. for i in list1:
6. print(i)
Output:

12
14
16
39
40

5. Membership

It returns true if a particular item exists in a particular list otherwise false.

Code

1. # membership of the list


2. # declaring the list
3. list1 = [100, 200, 300, 400, 500]
4. # true will be printed if value exists
5. # and false if not
6.
7. print(600 in list1)
8. print(700 in list1)
9. print(1040 in list1)
10.
11.print(300 in list1)
12.print(100 in list1)
13.print(500 in list1)
Output:

False
False
False
True
True
True

Iterating a List

A list can be iterated by using a for - in loop. A simple list containing four
strings, which can be iterated as follows.

Code

1. # iterating a list
2. list = ["John", "David", "James", "Jonathan"]
3. for i in list:
4. # The i variable will iterate over the elements of the List and contains each
element in each iteration.
5. print(i)
Output:

John
David
James
Jonathan
Adding Elements to the List

The append() function in Python can add a new item to the List. In any case,
the annex() capability can enhance the finish of the rundown.

Consider the accompanying model, where we take the components of the


rundown from the client and print the rundown on the control center.

Code

1. #Declaring the empty list


2. l =[]
3. #Number of elements will be entered by the user
4. n = int(input("Enter the number of elements in the list:"))
5. # for loop to take the input
6. for i in range(0,n):
7. # The input is taken from the user and added to the list as the item
8. l.append(input("Enter the item:"))
9. print("printing the list items..")
10.# traversal loop to print the list items
11.for i in l:
12. print(i, end = " ")
Output:

Enter the number of elements in the list:10


Enter the item:32
Enter the item:56
Enter the item:81
Enter the item:2
Enter the item:34
Enter the item:65
Enter the item:09
Enter the item:66
Enter the item:12
Enter the item:18
printing the list items..
32 56 81 2 34 65 09 66 12 18

Removing Elements from the List


The remove() function in Python can remove an element from the List. To
comprehend this idea, look at the example that follows.

Example -

Code

1. list = [0,1,2,3,4]
2. print("printing original list: ");
3. for i in list:
4. print(i,end=" ")
5. list.remove(2)
6. print("\nprinting the list after the removal of first element...")
7. for i in list:
8. print(i,end=" ")
Output:

printing original list:


01234
printing the list after the removal of first element...
0134

Python List Built-in Functions

Python provides the following built-in functions, which can be used with the
lists.

1. len()
2. max()
3. min()

len( )

It is used to calculate the length of the list.

Code

1. # size of the list


2. # declaring the list
3. list1 = [12, 16, 18, 20, 39, 40]
4. # finding length of the list
5. len(list1)
Output:

Max( )

It returns the maximum element of the list

Code

1. # maximum of the list


2. list1 = [103, 675, 321, 782, 200]
3. # large element in the list
4. print(max(list1))
Output:

782

Min( )

It returns the minimum element of the list

Code

1. # minimum of the list


2. list1 = [103, 675, 321, 782, 200]
3. # smallest element in the list
4. print(min(list1))
Output:

103

Let's have a look at the few list examples.

Example: 1- Create a program to eliminate the List's duplicate items.


Code

1. list1 = [1,2,2,3,55,98,65,65,13,29]
2. # Declare an empty list that will store unique values
3. list2 = []
4. for i in list1:
5. if i not in list2:
6. list2.append(i)
7. print(list2)
Output:

[1, 2, 3, 55, 98, 65, 13, 29]

Python Set
A Python set is the collection of the unordered items. Each element in the set
must be unique, immutable, and the sets remove the duplicate elements. Sets
are mutable which means we can modify it after its creation.

Unlike other collections in Python, there is no index attached to the elements


of the set, i.e., we cannot directly access any element of the set by the index.
However, we can print them all together, or we can get the list of elements by
looping through the set.

Creating a set

The set can be created by enclosing the comma-separated immutable items


with the curly braces {}. Python also provides the set() method, which can be
used to create the set by the passed sequence.

Example 1: Using curly braces

1. Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Satur


day", "Sunday"}
2. print(Days)
3. print(type(Days))
4. print("looping through the set elements ... ")
5. for i in Days:
6. print(i)
Output:
{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday',
'Wednesday'}
<class 'set'>
looping through the set elements ...
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday

Example 2: Using set() method

1. Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Sat


urday", "Sunday"])
2. print(Days)
3. print(type(Days))
4. print("looping through the set elements ... ")
5. for i in Days:
6. print(i)
Output:

{'Friday', 'Wednesday', 'Thursday', 'Saturday', 'Monday', 'Tuesday',


'Sunday'}
<class 'set'>
looping through the set elements ...
Friday
Wednesday
Thursday
Saturday
Monday
Tuesday
Sunday

It can contain any type of element such as integer, float, tuple etc. But mutable
elements (list, dictionary, set) can't be a member of set. Consider the following
example.
1. # Creating a set which have immutable elements
2. set1 = {1,2,3, "JavaTpoint", 20.5, 14}
3. print(type(set1))
4. #Creating a set which have mutable element
5. set2 = {1,2,3,["Javatpoint",4]}
6. print(type(set2))
Output:

<class 'set'>

Traceback (most recent call last)


<ipython-input-5-9605bb6fbc68> in <module>
4
5 #Creating a set which holds mutable elements
----> 6 set2 = {1,2,3,["Javatpoint",4]}
7 print(type(set2))

TypeError: unhashable type: 'list'

In the above code, we have created two sets, the set set1 have immutable
elements and set2 have one mutable element as a list. While checking the type
of set2, it raised an error, which means set can contain only immutable
elements.

Creating an empty set is a bit different because empty curly {} braces are also
used to create a dictionary as well. So Python provides the set() method used
without an argument to create an empty set.

1. # Empty curly braces will create dictionary


2. set3 = {}
3. print(type(set3))
4.
5. # Empty set using set() function
6. set4 = set()
7. print(type(set4))
Output:

<class 'dict'>
<class 'set'>
Let's see what happened if we provide the duplicate element to the set.

1. set5 = {1,2,4,4,5,8,9,9,10}
2. print("Return set with unique elements:",set5)
Output:

Return set with unique elements: {1, 2, 4, 5, 8, 9, 10}

In the above code, we can see that set5 consisted of multiple duplicate
elements when we printed it remove the duplicity from the set.

Adding items to the set

Python provides the add() method and update() method which can be used to
add some particular item to the set. The add() method is used to add a single
element whereas the update() method is used to add multiple elements to the
set. Consider the following example.

Example: 1 - Using add() method

1. Months = set(["January","February", "March", "April", "May", "June"])


2. print("\nprinting the original set ... ")
3. print(months)
4. print("\nAdding other months to the set...");
5. Months.add("July");
6. Months.add ("August");
7. print("\nPrinting the modified set...");
8. print(Months)
9. print("\nlooping through the set elements ... ")
10.for i in Months:
11. print(i)
Output:

printing the original set ...


{'February', 'May', 'April', 'March', 'June', 'January'}

Adding other months to the set...

Printing the modified set...


{'February', 'July', 'May', 'April', 'March', 'August', 'June', 'January'}
looping through the set elements ...
February
July
May
April
March
August
June
January

To add more than one item in the set, Python provides the update() method.
It accepts iterable as an argument.

Consider the following example.

Example - 2 Using update() function

1. Months = set(["January","February", "March", "April", "May", "June"])


2. print("\nprinting the original set ... ")
3. print(Months)
4. print("\nupdating the original set ... ")
5. Months.update(["July","August","September","October"]);
6. print("\nprinting the modified set ... ")
7. print(Months);
Output:

printing the original set ...


{'January', 'February', 'April', 'May', 'June', 'March'}

updating the original set ...


printing the modified set ...
{'January', 'February', 'April', 'August', 'October', 'May', 'June', 'July',
'September', 'March'}

Removing items from the set

Python provides the discard() method and remove() method which can be
used to remove the items from the set. The difference between these function,
using discard() function if the item does not exist in the set then the set remain
unchanged whereas remove() method will through an error.

Consider the following example.

Example-1 Using discard() method

1. months = set(["January","February", "March", "April", "May", "June"])


2. print("\nprinting the original set ... ")
3. print(months)
4. print("\nRemoving some months from the set...");
5. months.discard("January");
6. months.discard("May");
7. print("\nPrinting the modified set...");
8. print(months)
9. print("\nlooping through the set elements ... ")
10.for i in months:
11. print(i)
Output:

printing the original set ...


{'February', 'January', 'March', 'April', 'June', 'May'}

Removing some months from the set...

Printing the modified set...


{'February', 'March', 'April', 'June'}

looping through the set elements ...


February
March
April
June

Python provides also the remove() method to remove the item from the set.
Consider the following example to remove the items using remove() method.

Example-2 Using remove() function

1. months = set(["January","February", "March", "April", "May", "June"])


2. print("\nprinting the original set ... ")
3. print(months)
4. print("\nRemoving some months from the set...");
5. months.remove("January");
6. months.remove("May");
7. print("\nPrinting the modified set...");
8. print(months)
Output:

printing the original set ...


{'February', 'June', 'April', 'May', 'January', 'March'}

Removing some months from the set...

Printing the modified set...


{'February', 'June', 'April', 'March'}

We can also use the pop() method to remove the item. Generally, the pop()
method will always remove the last item but the set is unordered, we can't
determine which element will be popped from set.

Consider the following example to remove the item from the set using pop()
method.

1. Months = set(["January","February", "March", "April", "May", "June"])


2. print("\nprinting the original set ... ")
3. print(Months)
4. print("\nRemoving some months from the set...");
5. Months.pop();
6. Months.pop();
7. print("\nPrinting the modified set...");
8. print(Months)
Output:

printing the original set ...


{'June', 'January', 'May', 'April', 'February', 'March'}

Removing some months from the set...

Printing the modified set...


{'May', 'April', 'February', 'March'}
In the above code, the last element of the Month set is March but the pop()
method removed the June and January because the set is unordered and the
pop() method could not determine the last element of the set.

Python provides the clear() method to remove all the items from the set.

Consider the following example.

1. Months = set(["January","February", "March", "April", "May", "June"])


2. print("\nprinting the original set ... ")
3. print(Months)
4. print("\nRemoving all the items from the set...");
5. Months.clear()
6. print("\nPrinting the modified set...")
7. print(Months)
Output:

printing the original set ...


{'January', 'May', 'June', 'April', 'March', 'February'}

Removing all the items from the set...

Printing the modified set...


set()

Difference between discard() and remove()

Despite the fact that discard() and remove() method both perform the same
task, There is one main difference between discard() and remove().

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 raise an error.

Consider the following example.

Example-

1. Months = set(["January","February", "March", "April", "May", "June"])


2. print("\nprinting the original set ... ")
3. print(Months)
4. print("\nRemoving items through discard() method...");
5. Months.discard("Feb"); #will not give an error although the key feb is not av
ailable in the set
6. print("\nprinting the modified set...")
7. print(Months)
8. print("\nRemoving items through remove() method...");
9. Months.remove("Jan") #will give an error as the key jan is not available in th
e set.
10.print("\nPrinting the modified set...")
11.print(Months)
Output:

printing the original set ...


{'March', 'January', 'April', 'June', 'February', 'May'}

Removing items through discard() method...

printing the modified set...


{'March', 'January', 'April', 'June', 'February', 'May'}

Removing items through remove() method...


Traceback (most recent call last):
File "set.py", line 9, in
Months.remove("Jan")
KeyError: 'Jan'

Python Set Operations

Set can be performed mathematical operation such as union, intersection,


difference, and symmetric difference. Python provides the facility to carry out
these operations with operators or methods. We describe these operations as
follows.

Union of two Sets

To combine two or more sets into one set in Python, use the union() function.
All of the distinctive characteristics from each combined set are present in the
final set. As parameters, one or more sets may be passed to the union()
function. The function returns a copy of the set supplied as the lone parameter
if there is just one set. The method returns a new set containing all the different
items from all the arguments if more than one set is supplied as an argument.

Consider the following example to calculate the union of two sets.

Example 1: using union | operator

1. Days1 = {"Monday","Tuesday","Wednesday","Thursday", "Sunday"}


2. Days2 = {"Friday","Saturday","Sunday"}
3. print(Days1|Days2) #printing the union of the sets
Output:

{'Friday', 'Sunday', 'Saturday', 'Tuesday', 'Wednesday', 'Monday',


'Thursday'}

Python also provides the union() method which can also be used to calculate
the union of two sets. Consider the following example.

Example 2: using union() method

1. Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
2. Days2 = {"Friday","Saturday","Sunday"}
3. print(Days1.union(Days2)) #printing the union of the sets
Output:
{'Friday', 'Monday', 'Tuesday', 'Thursday', 'Wednesday', 'Sunday',
'Saturday'}

Now, we can also make the union of more than two sets using the union()
function, for example:

Program:

1. # Create three sets


2. set1 = {1, 2, 3}
3. set2 = {2, 3, 4}
4. set3 = {3, 4, 5}
5.
6. # Find the common elements between the three sets
7. common_elements = set1.union(set2, set3)
8.
9. # Print the common elements
10.print(common_elements)
Output:

{1, 2, 3, 4, 5}

The intersection of two sets

To discover what is common between two or more sets in Python, apply the
intersection() function. Only the items in all sets being compared are included
in the final set. One or more sets can also be used as the intersection() function
parameters. The function returns a copy of the set supplied as the lone
parameter if there is just one set. The method returns a new set that only
contains the elements in all the compared sets if multiple sets are supplied as
arguments.

The intersection of two sets can be performed by the and & operator or
the intersection() function. The intersection of the two sets is given as the set
of the elements that common in both sets.
Consider the following example.

Example 1: Using & operator

1. Days1 = {"Monday","Tuesday", "Wednesday", "Thursday"}


2. Days2 = {"Monday","Tuesday","Sunday", "Friday"}
3. print(Days1&Days2) #prints the intersection of the two sets
Output:

{'Monday', 'Tuesday'}

Example 2: Using intersection() method

1. set1 = {"Devansh","John", "David", "Martin"}


2. set2 = {"Steve", "Milan", "David", "Martin"}
3. print(set1.intersection(set2)) #prints the intersection of the two sets
Output:

{'Martin', 'David'}

Example 3:

1. set1 = {1,2,3,4,5,6,7}
2. set2 = {1,2,20,32,5,9}
3. set3 = set1.intersection(set2)
4. print(set3)
Output:

{1,2,5}

Similarly, as the same as union function, we can perform the intersection of


more than two sets at a time,

For Example:

Program

1. # Create three sets


2. set1 = {1, 2, 3}
3. set2 = {2, 3, 4}
4. set3 = {3, 4, 5}
5.
6. # Find the common elements between the three sets
7. common_elements = set1.intersection(set2, set3)
8.
9. # Print the common elements
10.print(common_elements)
Output:

{3}

The intersection_update() method

The intersection_update() method removes the items from the original set
that are not present in both the sets (all the sets if more than one are specified).

The intersection_update() method is different from the intersection() method


since it modifies the original set by removing the unwanted items, on the other
hand, the intersection() method returns a new set.

Consider the following example.

1. a = {"Devansh", "bob", "castle"}


2. b = {"castle", "dude", "emyway"}
3. c = {"fuson", "gaurav", "castle"}
4.
5. a.intersection_update(b, c)
6.
7. print(a)
Output:

{'castle'}

Difference between the two sets

The difference of two sets can be calculated by using the subtraction (-)
operator or intersection() method. Suppose there are two sets A and B, and
the difference is A-B that denotes the resulting set will be obtained that
element of A, which is not present in the set B.

Consider the following example.

Example 1 : Using subtraction ( - ) operator

1. Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}


2. Days2 = {"Monday", "Tuesday", "Sunday"}
3. print(Days1-Days2) #{"Wednesday", "Thursday" will be printed}
Output:

{'Thursday', 'Wednesday'}

Example 2 : Using difference() method


1. Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
2. Days2 = {"Monday", "Tuesday", "Sunday"}
3. print(Days1.difference(Days2)) # prints the difference of the two sets Days1
and Days2
Output:

{'Thursday', 'Wednesday'}

Symmetric Difference of two sets

In Python, the symmetric Difference between set1 and set2 is the set of
elements present in one set or the other but not in both sets. In other words,
the set of elements is in set1 or set2 but not in their intersection.

The Symmetric Difference of two sets can be computed using Python's


symmetric_difference() method. This method returns a new set containing all
the elements in either but not in both. Consider the following example:

Example - 1: Using ^ operator

1. a = {1,2,3,4,5,6}
2. b = {1,2,9,8,10}
3. c = a^b
4. print(c)
Output:
{3, 4, 5, 6, 8, 9, 10}

Example - 2: Using symmetric_difference() method

1. a = {1,2,3,4,5,6}
2. b = {1,2,9,8,10}
3. c = a.symmetric_difference(b)
4. print(c)
Output:

{3, 4, 5, 6, 8, 9, 10}

Set comparisons

In Python, you can compare sets to check if they are equal, if one set is a subset
or superset of another, or if two sets have elements in common.

Here are the set comparison operators available in Python:

o ==: checks if two sets have the same elements, regardless of their order.
o !=: checks if two sets are not equal.
o <: checks if the left set is a proper subset of the right set (i.e., all
elements in the left set are also in the right set, but the right set has
additional elements).
o <=: checks if the left set is a subset of the right set (i.e., all elements in
the left set are also in the right set).
o >: checks if the left set is a proper superset of the right set (i.e., all
elements in the right set are also in the left set, but the left set has
additional elements).
o >=: checks if the left set is a superset of the right set (i.e., all elements
in the right set are also in the left).
Consider the following example.

1. Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}


2. Days2 = {"Monday", "Tuesday"}
3. Days3 = {"Monday", "Tuesday", "Friday"}
4.
5. #Days1 is the superset of Days2 hence it will print true.
6. print (Days1>Days2)
7.
8. #prints false since Days1 is not the subset of Days2
9. print (Days1<Days2)
10.
11.#prints false since Days2 and Days3 are not equivalent
12.print (Days2 == Days3)
Output:

True
False
False

FrozenSets

In Python, a frozen set is an immutable version of the built-in set data type. It
is similar to a set, but its contents cannot be changed once a frozen set is
created.

Frozen set objects are unordered collections of unique elements, just like sets.
They can be used the same way as sets, except they cannot be modified.
Because they are immutable, frozen set objects can be used as elements of
other sets or dictionary keys, while standard sets cannot.

One of the main advantages of using frozen set objects is that they are
hashable, meaning they can be used as keys in dictionaries or as elements of
other sets. Their contents cannot change, so their hash values remain constant.
Standard sets are not hashable because they can be modified, so their hash
values can change.

Frozen set objects support many of the assets of the same operation, such as
union, intersection, Difference, and symmetric Difference. They also support
operations that do not modify the frozen set, such as len(), min(), max(), and
in.

Consider the following example to create the frozen set.

1. Frozenset = frozenset([1,2,3,4,5])
2. print(type(Frozenset))
3. print("\nprinting the content of frozen set...")
4. for i in Frozenset:
5. print(i);
6. Frozenset.add(6) #gives an error since we cannot change the content of Froz
enset after creation
Output:

<class 'frozenset'>

printing the content of frozen set...


1
2
3
4
5
Traceback (most recent call last):
File "set.py", line 6, in <module>
Frozenset.add(6) #gives an error since we can change the content of
Frozenset after creation
AttributeError: 'frozenset' object has no attribute 'add'

Frozenset for the dictionary

If we pass the dictionary as the sequence inside the frozenset() method, it will
take only the keys from the dictionary and returns a frozenset that contains the
key of the dictionary as its elements.

Consider the following example.

1. Dictionary = {"Name":"John", "Country":"USA", "ID":101}


2. print(type(Dictionary))
3. Frozenset = frozenset(Dictionary); #Frozenset will contain the keys of the di
ctionary
4. print(type(Frozenset))
5. for i in Frozenset:
6. print(i)
Output:

<class 'dict'>
<class 'frozenset'>
Name
Country
ID

Set Programming Example

Example - 1: Write a program to remove the given number from the set.

1. my_set = {1,2,3,4,5,6,12,24}
2. n = int(input("Enter the number you want to remove"))
3. my_set.discard(n)
4. print("After Removing:",my_set)
Output:

Enter the number you want to remove:12


After Removing: {1, 2, 3, 4, 5, 6, 24}

Example - 2: Write a program to add multiple elements to the set.

1. set1 = set([1,2,4,"John","CS"])
2. set1.update(["Apple","Mango","Grapes"])
3. print(set1)
Output:

{1, 2, 4, 'Apple', 'John', 'CS', 'Mango', 'Grapes'}

Example - 3: Write a program to find the union between two set.

1. set1 = set(["Peter","Joseph", 65,59,96])


2. set2 = set(["Peter",1,2,"Joseph"])
3. set3 = set1.union(set2)
4. print(set3)
Output:

{96, 65, 2, 'Joseph', 1, 'Peter', 59}

Example- 4: Write a program to find the intersection between two sets.


1. set1 = {23,44,56,67,90,45,"Javatpoint"}
2. set2 = {13,23,56,76,"Sachin"}
3. set3 = set1.intersection(set2)
4. print(set3)
Output:

{56, 23}

Example - 5: Write the program to add element to the frozenset.

1. set1 = {23,44,56,67,90,45,"Javatpoint"}
2. set2 = {13,23,56,76,"Sachin"}
3. set3 = set1.intersection(set2)
4. print(set3)
Output:

TypeError: 'frozenset' object does not support item assignment

Above code raised an error because frozensets are immutable and can't be
changed after creation.

Example - 6: Write the program to find the issuperset, issubset and superset.

1. set1 = set(["Peter","James","Camroon","Ricky","Donald"])
2. set2 = set(["Camroon","Washington","Peter"])
3. set3 = set(["Peter"])
4.
5. issubset = set1 >= set2
6. print(issubset)
7. issuperset = set1 <= set2
8. print(issuperset)
9. issubset = set3 <= set2
10.print(issubset)
11.issuperset = set2 >= set3
12.print(issuperset)
Output:

False
False
True
True

Python Tuples
A comma-separated group of items is called a Python triple. The ordering,
settled items, and reiterations of a tuple are to some degree like those of a
rundown, but in contrast to a rundown, a tuple is unchanging.

The main difference between the two is that we cannot alter the components
of a tuple once they have been assigned. On the other hand, we can edit the
contents of a list.

Example

1. ("Suzuki", "Audi", "BMW"," Skoda ") is a tuple.

Features of Python Tuple

o Tuples are an immutable data type, meaning their elements cannot be


changed after they are generated.
o Each element in a tuple has a specific order that will never change
because tuples are ordered sequences.

Forming a Tuple:

All the objects-also known as "elements"-must be separated by a comma,


enclosed in parenthesis (). Although parentheses are not required, they are
recommended.

Any number of items, including those with various data types (dictionary,
string, float, list, etc.), can be contained in a tuple.

Code

1. # Python program to show how to create a tuple


2. # Creating an empty tuple
3. empty_tuple = ()
4. print("Empty tuple: ", empty_tuple)
5.
6. # Creating tuple having integers
7. int_tuple = (4, 6, 8, 10, 12, 14)
8. print("Tuple with integers: ", int_tuple)
9.
10.# Creating a tuple having objects of different data types
11.mixed_tuple = (4, "Python", 9.3)
12.print("Tuple with different data types: ", mixed_tuple)
13.
14.# Creating a nested tuple
15.nested_tuple = ("Python", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))
16.print("A nested tuple: ", nested_tuple)
Output:

Empty tuple: ()
Tuple with integers: (4, 6, 8, 10, 12, 14)
Tuple with different data types: (4, 'Python', 9.3)
A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))

Parentheses are not necessary for the construction of multiples. This is known
as triple pressing.

Code

1. # Python program to create a tuple without using parentheses


2. # Creating a tuple
3. tuple_ = 4, 5.7, "Tuples", ["Python", "Tuples"]
4. # Displaying the tuple created
5. print(tuple_)
6. # Checking the data type of object tuple_
7. print(type(tuple_) )
8. # Trying to modify tuple_
9. try:
10. tuple_[1] = 4.2
11.except:
12. print(TypeError )
Output:
(4, 5.7, 'Tuples', ['Python', 'Tuples'])
<class 'tuple'>
<class 'TypeError'>

The development of a tuple from a solitary part may be complex.

Essentially adding a bracket around the component is lacking. A comma must


separate the element to be recognized as a tuple.

Code

1. # Python program to show how to create a tuple having a single element


2. single_tuple = ("Tuple")
3. print( type(single_tuple) )
4. # Creating a tuple that has only one element
5. single_tuple = ("Tuple",)
6. print( type(single_tuple) )
7. # Creating tuple without parentheses
8. single_tuple = "Tuple",
9. print( type(single_tuple) )
Output:

<class 'str'>
<class 'tuple'>
<class 'tuple'>

Accessing Tuple Elements

A tuple's objects can be accessed in a variety of ways.

Indexing

Indexing We can use the index operator [] to access an object in a tuple, where
the index starts at 0.

The indices of a tuple with five items will range from 0 to 4. An Index Error
will be raised assuming we attempt to get to a list from the Tuple that is outside
the scope of the tuple record. An index above four will be out of range in this
scenario.
Because the index in Python must be an integer, we cannot provide an index
of a floating data type or any other type. If we provide a floating index, the
result will be TypeError.

The method by which elements can be accessed through nested tuples can be
seen in the example below.

Code

1. # Python program to show how to access tuple elements


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Collection")
4. print(tuple_[0])
5. print(tuple_[1])
6. # trying to access element index more than the length of a tuple
7. try:
8. print(tuple_[5])
9. except Exception as e:
10. print(e)
11.# trying to access elements through the index of floating data type
12.try:
13. print(tuple_[1.0])
14.except Exception as e:
15. print(e)
16.# Creating a nested tuple
17.nested_tuple = ("Tuple", [4, 6, 2, 6], (6, 2, 6, 7))
18.
19.# Accessing the index of a nested tuple
20.print(nested_tuple[0][3])
21.print(nested_tuple[1][1])
Output:

Python
Tuple
tuple index out of range
tuple indices must be integers or slices, not float
l
6

o Negative Indexing
Python's sequence objects support negative indexing.

The last thing of the assortment is addressed by - 1, the second last thing by -
2, etc.

Code

1. # Python program to show how negative indexing works in Python tuples


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Collection")
4. # Printing elements using negative indices
5. print("Element at -1 index: ", tuple_[-1])
6. print("Elements between -4 and -1 are: ", tuple_[-4:-1])
Output:

Element at -1 index: Collection


Elements between -4 and -1 are: ('Python', 'Tuple', 'Ordered')

Slicing

Tuple slicing is a common practice in Python and the most common way for
programmers to deal with practical issues. Look at a tuple in Python. Slice a
tuple to access a variety of its elements. Using the colon as a straightforward
slicing operator (:) is one strategy.

To gain access to various tuple elements, we can use the slicing operator colon
(:).

Code

1. # Python program to show how slicing works in Python tuples


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects
")
4. # Using slicing to access elements of the tuple
5. print("Elements between indices 1 and 3: ", tuple_[1:3])
6. # Using negative indexing in slicing
7. print("Elements between indices 0 and -4: ", tuple_[:-4])
8. # Printing the entire tuple by using the default start and end values.
9. print("Entire tuple: ", tuple_[:])
Output:
Elements between indices 1 and 3: ('Tuple', 'Ordered')
Elements between indices 0 and -4: ('Python', 'Tuple')
Entire tuple: ('Python', 'Tuple', 'Ordered', 'Immutable', 'Collection',
'Objects')

Deleting a Tuple

A tuple's parts can't be modified, as was recently said. We are unable to


eliminate or remove tuple components as a result.

However, the keyword del can completely delete a tuple.

Code

1. # Python program to show how to delete elements of a Python tuple


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects
")
4. # Deleting a particular element of the tuple
5. try:
6. del tuple_[3]
7. print(tuple_)
8. except Exception as e:
9. print(e)
10.# Deleting the variable from the global space of the program
11.del tuple_
12.# Trying accessing the tuple after deleting it
13.try:
14. print(tuple_)
15.except Exception as e:
16. print(e)
Output:

'tuple' object does not support item deletion


name 'tuple_' is not defined

Repetition Tuples in Python


Code

1. # Python program to show repetition in tuples


2. tuple_ = ('Python',"Tuples")
3. print("Original tuple is: ", tuple_)
4. # Repeting the tuple elements
5. tuple_ = tuple_ * 3
6. print("New tuple is: ", tuple_)
Output:

Original tuple is: ('Python', 'Tuples')


New tuple is: ('Python', 'Tuples', 'Python', 'Tuples', 'Python', 'Tuples')

Tuple Methods

Like the list, Python Tuples is a collection of immutable objects. There are a
few ways to work with tuples in Python. With some examples, this essay will
go over these two approaches in detail.

The following are some examples of these methods.

o Count () Method
The times the predetermined component happens in the Tuple is returned by
the count () capability of the Tuple.

Code

1. # Creating tuples
2. T1 = (0, 1, 5, 6, 7, 2, 2, 4, 2, 3, 2, 3, 1, 3, 2)
3. T2 = ('python', 'java', 'python', 'Tpoint', 'python', 'java')
4. # counting the appearance of 3
5. res = T1.count(2)
6. print('Count of 2 in T1 is:', res)
7. # counting the appearance of java
8. res = T2.count('java')
9. print('Count of Java in T2 is:', res)
Output:

Count of 2 in T1 is: 5
Count of java in T2 is: 2

Index() Method:

The Index() function returns the first instance of the requested element from
the Tuple.

Parameters:

o The thing that must be looked for.


o Start: (Optional) the index that is used to begin the final (optional)
search: The most recent index from which the search is carried out
o Index Method
Code

1. # Creating tuples
2. Tuple_data = (0, 1, 2, 3, 2, 3, 1, 3, 2)
3. # getting the index of 3
4. res = Tuple_data.index(3)
5. print('First occurrence of 1 is', res)
6. # getting the index of 3 after 4th
7. # index
8. res = Tuple_data.index(3, 4)
9. print('First occurrence of 1 after 4th index is:', res)
Output:

First occurrence of 1 is 2
First occurrence of 1 after 4th index is: 6

Tuple Membership Test

Utilizing the watchword, we can decide whether a thing is available in the


given Tuple.

Code

1. # Python program to show how to perform membership test for tuples


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Ordere
d")
4. # In operator
5. print('Tuple' in tuple_)
6. print('Items' in tuple_)
7. # Not in operator
8. print('Immutable' not in tuple_)
9. print('Items' not in tuple_)
Output:

True
False
False
True

Iterating Through a Tuple

A for loop can be used to iterate through each tuple element.

Code

1. # Python program to show how to iterate over tuple elements


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable")
4. # Iterating over tuple elements using a for loop
5. for item in tuple_:
6. print(item)
Output:

Python
Tuple
Ordered
Immutable

Changing a Tuple

Tuples, instead of records, are permanent articles.


This suggests that once the elements of a tuple have been defined, we cannot
change them. However, the nested elements can be altered if the element itself
is a changeable data type like a list.

Multiple values can be assigned to a tuple through reassignment.

Code

1. # Python program to show that Python tuples are immutable objects


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable", [1,2,3,4])
4. # Trying to change the element at index 2
5. try:
6. tuple_[2] = "Items"
7. print(tuple_)
8. except Exception as e:
9. print( e )
10.# But inside a tuple, we can change elements of a mutable object
11.tuple_[-1][2] = 10
12.print(tuple_)
13.# Changing the whole tuple
14.tuple_ = ("Python", "Items")
15.print(tuple_)
Output:

'tuple' object does not support item assignment


('Python', 'Tuple', 'Ordered', 'Immutable', [1, 2, 10, 4])
('Python', 'Items')

The + operator can be used to combine multiple tuples into one. This
phenomenon is known as concatenation.

We can also repeat the elements of a tuple a predetermined number of times


by using the * operator. This is already demonstrated above.

The aftereffects of the tasks + and * are new tuples.

Code

1. # Python program to show how to concatenate tuples


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable")
4. # Adding a tuple to the tuple_
5. print(tuple_ + (4, 5, 6))
Output:

('Python', 'Tuple', 'Ordered', 'Immutable', 4, 5, 6)

Tuples have the following advantages over lists:

o Triples take less time than lists do.


o Due to tuples, the code is protected from accidental modifications. It is
desirable to store non-changing information in "tuples" instead of
"records" if a program expects it.
o A tuple can be used as a dictionary key if it contains immutable values
like strings, numbers, or another tuple. "Lists" cannot be utilized as
dictionary keys because they are mutable.

Python Dictionary
Dictionaries are a useful data structure for storing data in Python because they
are capable of imitating real-world data arrangements where a certain value
exists for a given key.

The data is stored as key-value pairs using a Python dictionary.

o This data structure is mutable


o The components of dictionary were made using keys and values.
o Keys must only have one component.
o Values can be of any type, including integer, list, and tuple.
A dictionary is, in other words, a group of key-value pairs, where the values
can be any Python object. The keys, in contrast, are immutable Python objects,
such as strings, tuples, or numbers. Dictionary entries are ordered as of Python
version 3.7. In Python 3.6 and before, dictionaries are generally unordered.

Creating the Dictionary

Curly brackets are the simplest way to generate a Python dictionary, although
there are other approaches as well. With many key-value pairs surrounded in
curly brackets and a colon separating each key from its value, the dictionary
can be built. (:). The following provides the syntax for defining the dictionary.
Syntax:

1. Dict = {"Name": "Gayle", "Age": 25}


In the above dictionary Dict, The keys Name and Age are the strings which
comes under the category of an immutable object.

Let's see an example to create a dictionary and print its content.

Code

1. Employee = {"Name": "Johnny", "Age": 32, "salary":26000,"Company":"^T


CS"}
2. print(type(Employee))
3. print("printing Employee data .... ")
4. print(Employee)
Output

<class 'dict'>
printing Employee data ....
{'Name': 'Johnny', 'Age': 32, 'salary': 26000, 'Company': TCS}

Python provides the built-in function dict() method which is also used to
create the dictionary.

The empty curly braces {} is used to create empty dictionary.

Code

1. # Creating an empty Dictionary


2. Dict = {}
3. print("Empty Dictionary: ")
4. print(Dict)
5.
6. # Creating a Dictionary
7. # with dict() method
8. Dict = dict({1: 'Hcl', 2: 'WIPRO', 3:'Facebook'})
9. print("\nCreate Dictionary by using dict(): ")
10.print(Dict)
11.
12.# Creating a Dictionary
13.# with each item as a Pair
14.Dict = dict([(4, 'Rinku'), (2, Singh)])
15.print("\nDictionary with each item as a pair: ")
16.print(Dict)
Output

Empty Dictionary:
{}

Create Dictionary by using dict():


{1: 'Hcl', 2: 'WIPRO', 3: 'Facebook'}

Dictionary with each item as a pair:


{4: 'Rinku', 2: 'Singh'}

Accessing the dictionary values

To access data contained in lists and tuples, indexing has been studied. The
keys of the dictionary can be used to obtain the values because they are unique
from one another. The following method can be used to access dictionary
values.

Code

1. Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPR


O"}
2. print(type(Employee))
3. print("printing Employee data .... ")
4. print("Name : %s" %Employee["Name"])
5. print("Age : %d" %Employee["Age"])
6. print("Salary : %d" %Employee["salary"])
7. print("Company : %s" %Employee["Company"])
Output

ee["Company"])
Output
<class 'dict'>
printing Employee data ....
Name : Dev
Age : 20
Salary : 45000
Company : WIPRO

Python provides us with an alternative to use the get() method to access the
dictionary values. It would give the same result as given by the indexing.

Adding Dictionary Values

The dictionary is a mutable data type, and utilising the right keys allows you
to change its values. Dict[key] = value and the value can both be modified. An
existing value can also be updated using the update() method.

Note: The value is updated if the key-value pair is already present in the
dictionary. Otherwise, the dictionary's newly added keys.
Let's see an example to update the dictionary values.

Example - 1:

Code

1. # Creating an empty Dictionary


2. Dict = {}
3. print("Empty Dictionary: ")
4. print(Dict)
5.
6. # Adding elements to dictionary one at a time
7. Dict[0] = 'Peter'
8. Dict[2] = 'Joseph'
9. Dict[3] = 'Ricky'
10.print("\nDictionary after adding 3 elements: ")
11.print(Dict)
12.
13.# Adding set of values
14.# with a single Key
15.# The Emp_ages doesn't exist to dictionary
16.Dict['Emp_ages'] = 20, 33, 24
17.print("\nDictionary after adding 3 elements: ")
18.print(Dict)
19.
20.# Updating existing Key's Value
21.Dict[3] = 'JavaTpoint'
22.print("\nUpdated key value: ")
23.print(Dict)
Output

Empty Dictionary:
{}

Dictionary after adding 3 elements:


{0: 'Peter', 2: 'Joseph', 3: 'Ricky'}

Dictionary after adding 3 elements:


{0: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Emp_ages': (20, 33, 24)}

Updated key value:


{0: 'Peter', 2: 'Joseph', 3: 'JavaTpoint', 'Emp_ages': (20, 33, 24)}

Example - 2:

Code

1. Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPR


O"}
2. print(type(Employee))
3. print("printing Employee data .... ")
4. print(Employee)
5. print("Enter the details of the new employee....");
6. Employee["Name"] = input("Name: ");
7. Employee["Age"] = int(input("Age: "));
8. Employee["salary"] = int(input("Salary: "));
9. Employee["Company"] = input("Company:");
10.print("printing the new data");
11.print(Employee)
Output

<class 'dict'>
printing Employee data ....
Employee = {"Name": "Dev", "Age": 20,
"salary":45000,"Company":"WIPRO"} Enter the details of the new
employee....
Name: Sunny
Age: 38
Salary: 39000
Company:Hcl
printing the new data
{'Name': 'Sunny', 'Age': 38, 'salary': 39000, 'Company': 'Hcl'}

Deleting Elements using del Keyword

The items of the dictionary can be deleted by using the del keyword as given
below.

Code

1. Employee = {"Name": "David", "Age": 30, "salary":55000,"Company":"WI


PRO"}
2. print(type(Employee))
3. print("printing Employee data .... ")
4. print(Employee)
5. print("Deleting some of the employee data")
6. del Employee["Name"]
7. del Employee["Company"]
8. print("printing the modified information ")
9. print(Employee)
10.print("Deleting the dictionary: Employee");
11.del Employee
12.print("Lets try to print it again ");
13.print(Employee)
Output

<class 'dict'>
printing Employee data ....
{'Name': 'David', 'Age': 30, 'salary': 55000, 'Company': 'WIPRO'}
Deleting some of the employee data
printing the modified information
{'Age': 30, 'salary': 55000}
Deleting the dictionary: Employee
Lets try to print it again
NameError: name 'Employee' is not defined.
The last print statement in the above code, it raised an error because we tried
to print the Employee dictionary that already deleted.

Deleting Elements using pop() Method

A dictionary is a group of key-value pairs in Python. You can retrieve, insert,


and remove items using this unordered, mutable data type by using their keys.
The pop() method is one of the ways to get rid of elements from a dictionary.
In this post, we'll talk about how to remove items from a Python dictionary
using the pop() method.

The value connected to a specific key in a dictionary is removed using the


pop() method, which then returns the value. The key of the element to be
removed is the only argument needed. The pop() method can be used in the
following ways:

Code

1. # Creating a Dictionary
2. Dict1 = {1: 'JavaTpoint', 2: 'Educational', 3: 'Website'}
3. # Deleting a key
4. # using pop() method
5. pop_key = Dict1.pop(2)
6. print(Dict1)
Output

{1: 'JavaTpoint', 3: 'Website'}

Additionally, Python offers built-in functions popitem() and clear() for


removing dictionary items. In contrast to the clear() method, which removes
all of the elements from the entire dictionary, popitem() removes any element
from a dictionary.

Iterating Dictionary

A dictionary can be iterated using for loop as given below.

Example 1

Code

1. # for loop to print all the keys of a dictionary


2. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIP
RO"}
3. for x in Employee:
4. print(x)
Output

Name
Age
salary
Company

Example 2

Code

1. #for loop to print all the values of the dictionary


2. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIP
RO"} for x in Employee:
3. print(Employee[x])
Output

John
29
25000
WIPRO

Example - 3

Code

1. #for loop to print the values of the dictionary by using values() method.
2. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIP
RO"}
3. for x in Employee.values():
4. print(x)
Output

John
29
25000
WIPRO

Example 4

Code

1. #for loop to print the items of the dictionary by using items() method
2. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIP
RO"}
3. for x in Employee.items():
4. print(x)
Output

('Name', 'John')
('Age', 29)
('salary', 25000)
('Company', 'WIPRO')

Properties of Dictionary Keys

1. In the dictionary, we cannot store multiple values for the same keys. If we
pass more than one value for a single key, then the value which is last assigned
is considered as the value of the key.

Consider the following example.

Code

1. Employee={"Name":"John","Age":29,"Salary":25000,"Company":"WIPRO
","Name":
2. "John"}
3. for x,y in Employee.items():
4. print(x,y)
Output

Name John
Age 29
Salary 25000
Company WIPRO

2. The key cannot belong to any mutable object in Python. Numbers, strings,
or tuples can be used as the key, however mutable objects like lists cannot be
used as the key in a dictionary.

Consider the following example.

Code

1. Employee = {"Name": "John", "Age": 29, "salary":26000,"Company":"WIP


RO",[100,201,301]:"Department ID"}
2. for x,y in Employee.items():
3. print(x,y)
Output

Traceback (most recent call last):


File "dictionary.py", line 1, in
Employee = {"Name": "John", "Age": 29,
"salary":26000,"Company":"WIPRO",[100,201,301]:"Department ID"}
TypeError: unhashable type: 'list'

Built-in Dictionary Functions

A function is a method that can be used on a construct to yield a value.


Additionally, the construct is unaltered. A few of the Python methods can be
combined with a Python dictionary.

The built-in Python dictionary methods are listed below, along with a brief
description.

o len()
The dictionary's length is returned via the len() function in Python. The string
is lengthened by one for each key-value pair.

Code

1. dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}


2. len(dict)
Output

o any()
Like how it does with lists and tuples, the any() method returns True indeed if
one dictionary key does have a Boolean expression that evaluates to True.

Code

1. dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}


2. any({'':'','':'','3':''})
Output

True

o all()
Unlike in any() method, all() only returns True if each of the dictionary's keys
contain a True Boolean value.

Code

1. dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}


2. all({1:'',2:'','':''})
Output

False

o sorted()
Like it does with lists and tuples, the sorted() method returns an ordered series
of the dictionary's keys. The ascending sorting has no effect on the original
Python dictionary.

Code
1. dict = {7: "Ayan", 5: "Bunny", 8: "Ram", 1: "Bheem"}
2. sorted(dict)
Output

[ 1, 5, 7, 8]

Built-in Dictionary methods

The built-in python dictionary methods along with the description and Code
are given below.

o clear()
It is mainly used to delete all the items of the dictionary.

Code

1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # clear() method
4. dict.clear()
5. print(dict)
Output

{}

o copy()
It returns a shallow copy of the dictionary which is created.

Code

1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # copy() method
4. dict_demo = dict.copy()
5. print(dict_demo)
Output
{1: 'Hcl', 2: 'WIPRO', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}

o pop()
It mainly eliminates the element using the defined key.

Code

1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # pop() method
4. dict_demo = dict.copy()
5. x = dict_demo.pop(1)
6. print(x)
Output

{2: 'WIPRO', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}

popitem()

removes the most recent key-value pair entered

Code

1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # popitem() method
4. dict_demo.popitem()
5. print(dict_demo)
Output

{1: 'Hcl', 2: 'WIPRO', 3: 'Facebook'}

o keys()
It returns all the keys of the dictionary.

Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # keys() method
4. print(dict_demo.keys())
Output

dict_keys([1, 2, 3, 4, 5])

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

Code

1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # items() method
4. print(dict_demo.items())
Output

dict_items([(1, 'Hcl'), (2, 'WIPRO'), (3, 'Facebook'), (4, 'Amazon'), (5,


'Flipkart')])

o get()
It is used to get the value specified for the passed key.

Code

1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # get() method
4. print(dict_demo.get(3))
Output

Facebook

o update()
It mainly updates all the dictionary by adding the key-value pair of dict2 to
this dictionary.

Code

1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # update() method
4. dict_demo.update({3: "TCS"})
5. print(dict_demo)
Output

{1: 'Hcl', 2: 'WIPRO', 3: 'TCS'}

o values()
It returns all the values of the dictionary with respect to given input.

Code

1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # values() method
4. print(dict_demo.values())
Output

dict_values(['Hcl', 'WIPRO', 'TCS'])

File handling

File handling in Python is a crucial skill for managing data storage and
retrieval. Here’s a quick overview of how to work with files in Python:

### Basic File Operations

1. **Opening a File**:
Use the `open()` function to open a file. You can specify the mode:
- `'r'`: Read (default mode)
- `'w'`: Write (creates a new file or truncates an existing one)
- `'a'`: Append (adds to an existing file)
- `'b'`: Binary mode (for non-text files)

```python
file = open('example.txt', 'r')
```

2. **Reading from a File**:


You can read the content using various methods:
- `read()`: Reads the entire file.
- `readline()`: Reads one line at a time.
- `readlines()`: Reads all lines into a list.

```python
content = file.read()
```

3. **Writing to a File**:
Use the `write()` or `writelines()` methods to write data.

```python
with open('example.txt', 'w') as file:
file.write("Hello, World!")
```

4. **Closing a File**:
Always close the file after operations to free up system resources.

```python
file.close()
```

Alternatively, using the `with` statement automatically closes the file:

```python
with open('example.txt', 'r') as file:
content = file.read()
```

### Example: Reading and Writing Files


Here’s a simple example that demonstrates reading from and writing to a text
file:

```python
# Writing to a file
with open('example.txt', 'w') as file:
file.write("Hello, World!\n")
file.write("Welcome to file handling in Python.")

# Reading from a file


with open('example.txt', 'r') as file:
content = file.read()
print(content)
```

### Handling Exceptions

To handle errors like file not found, you can use a `try` and `except` block:

```python
try:
with open('non_existent_file.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("The file does not exist.")
```

### Working with Binary Files

For binary files, use `'rb'` or `'wb'` modes:

```python
# Writing a binary file
with open('image.png', 'wb') as file:
file.write(binary_data)

# Reading a binary file


with open('image.png', 'rb') as file:
binary_data = file.read()
```

Writing structures to a file


Writing structured data to a file in Python can be done in several ways,
depending on the format you want to use. Here are a few common methods
for writing structured data:

### 1. Writing to a Text File

If you're using simple structures like lists or dictionaries, you can write them
to a text file in a readable format:

```python
data = {
"name": "Alice",
"age": 30,
"city": "New York"
}

with open('data.txt', 'w') as file:


for key, value in data.items():
file.write(f"{key}: {value}\n")
```

### 2. Using CSV Format

For tabular data, the CSV (Comma-Separated Values) format is very useful.
You can use the `csv` module:

```python
import csv

data = [
["Name", "Age", "City"],
["Alice", 30, "New York"],
["Bob", 25, "Los Angeles"],
]

with open('data.csv', 'w', newline='') as file:


writer = csv.writer(file)
writer.writerows(data)
```

### 3. Using JSON Format


If you're dealing with more complex data structures (like nested dictionaries
or lists), JSON is a great choice. You can use the `json` module:

```python
import json

data = {
"people": [
{"name": "Alice", "age": 30, "city": "New York"},
{"name": "Bob", "age": 25, "city": "Los Angeles"}
]
}

with open('data.json', 'w') as file:


json.dump(data, file, indent=4)
```

### 4. Using Pickle for Python Objects

If you want to serialize and save Python objects directly, you can use the
`pickle` module. This is useful for more complex Python objects:

```python
import pickle

data = {
"name": "Alice",
"age": 30,
"hobbies": ["reading", "hiking", "coding"]
}

with open('data.pkl', 'wb') as file:


pickle.dump(data, file)
```

Errors and exception


Errors and exceptions in Python are important concepts for handling
unexpected situations in your code. Here's a breakdown of how they work
and how to manage them effectively:

### Types of Errors

1. **Syntax Errors**: These occur when the Python interpreter encounters


incorrect syntax. For example:

```python
print("Hello, World!"
```

This will raise a `SyntaxError`.

2. **Runtime Errors**: These occur during execution and can lead to


program crashes. Common examples include:
- **ZeroDivisionError**: Division by zero.
- **TypeError**: Performing an operation on incompatible types.
- **NameError**: Using a variable that hasn’t been defined.

Example:

```python
result = 10 / 0 # Raises ZeroDivisionError
```

3. **Logical Errors**: These don’t raise exceptions but lead to incorrect


behavior or output.

### Exception Handling

Python provides a robust way to handle exceptions using the `try`, `except`,
`else`, and `finally` blocks:

#### Basic Try-Except

You can use a `try` block to wrap code that may raise an exception and an
`except` block to handle it.

```python
try:
result = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
```

#### Catching Multiple Exceptions

You can catch multiple exceptions by specifying them as a tuple:

```python
try:
# some code that may raise an exception
result = int("abc") # Raises ValueError
except (ValueError, TypeError) as e:
print(f"An error occurred: {e}")
```

#### Using Else

The `else` block runs if the `try` block does not raise an exception:

```python
try:
result = 10 / 2
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print(f"Result is {result}")
```

#### Finally Block

The `finally` block runs regardless of whether an exception was raised or


not. It’s useful for cleanup actions, like closing files or releasing resources.

```python
try:
file = open('data.txt', 'r')
content = file.read()
except FileNotFoundError:
print("File not found.")
finally:
file.close() # This will run no matter what
```
### Raising Exceptions

You can also raise exceptions intentionally using the `raise` keyword:

```python
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative.")
return age

try:
check_age(-5)
except ValueError as e:
print(e)
```

### Custom Exceptions

You can define your own exceptions by subclassing the built-in `Exception`
class:

```python
class CustomError(Exception):
pass

try:
raise CustomError("This is a custom error.")
except CustomError as e:
print(e)
```

Handling exception

Handling exceptions in Python is a key aspect of writing robust and reliable


code. It allows you to gracefully manage errors that may occur during
program execution. Here’s a detailed guide on how to handle exceptions
effectively:

### Basic Exception Handling


The basic structure for handling exceptions uses the `try` and `except`
blocks:

```python
try:
# Code that may raise an exception
result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
# Code that runs if the specified exception occurs
print("You can't divide by zero!")
```

### Catching Multiple Exceptions

You can catch multiple exceptions by listing them in a tuple:

```python
try:
# Some code that may raise an exception
value = int("abc") # This will raise a ValueError
except (ValueError, TypeError) as e:
print(f"An error occurred: {e}")
```

### Using Else

The `else` block runs if the `try` block does not raise any exceptions:

```python
try:
result = 10 / 2
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print(f"Result is {result}")
```

### Finally Block

The `finally` block will execute no matter what, whether an exception was
raised or not. This is useful for cleanup tasks, like closing files or releasing
resources:
```python
try:
file = open('data.txt', 'r')
content = file.read()
except FileNotFoundError:
print("File not found.")
finally:
file.close() # This will run regardless of whether an exception occurred
```

### Raising Exceptions

You can raise exceptions intentionally using the `raise` keyword, which is
useful for enforcing conditions in your code:

```python
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative.")
return age

try:
check_age(-5)
except ValueError as e:
print(e)
```

### Custom Exceptions

You can create your own exception classes by subclassing the built-in
`Exception` class. This allows you to define specific error conditions for
your application:

```python
class CustomError(Exception):
pass

try:
raise CustomError("This is a custom error.")
except CustomError as e:
print(e)
```
### Best Practices

1. **Be Specific**: Catch specific exceptions rather than using a generic


`except` statement. This helps you understand the type of error that occurred.

```python
try:
# Some code
except ValueError:
# Handle ValueError
```

2. **Avoid Silent Failures**: Don’t use `except Exception:` without


handling the error. This can make debugging difficult.

3. **Use Finally for Cleanup**: Always use the `finally` block for actions
that must occur regardless of success or failure (like closing files).

4. **Log Errors**: Consider logging errors for later analysis, especially in


production code. The `logging` module is useful for this.

You might also like