Python UNIT3 Notes-1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

Python Second Chapter Notes-GSM

UNIT III

LIST
A list in Python is used to store the sequence of various types of data. Python lists are
mutable type its mean we can modify its element after it created. However, Python consists
of six data-types that are capable to store the sequences, but the most common and reliable
type is the list.

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 define as below

1. L1 = ["John", 102, "USA"]


2. L2 = [1, 2, 3, 4, 5, 6]

IIf we try to print the type of L1, L2, and L3 using type() function then it will come out to be
a list.

1. print(type(L1))
2. print(type(L2))

Output:

<class 'list'>
<class 'list'>
Characteristics of Lists

The list has the following characteristics:

o The lists are ordered.


o The element of the list can access by index.
o The lists are the mutable type.
o The lists are mutable types.
o A list can store the number of various elements.

Let's check the first statement that lists are the ordered.

1. a = [1,2,"Peter",4.50,"Ricky",5,6]
Jain College of BBA BCA & Commerce, Belagavi
Page 1
Python Second Chapter Notes-GSM

2. b = [1,2,5,"Peter",4.50,"Ricky",6]
3. a ==b

Output:

False

Both lists have consisted of the same elements, but the second list changed the index
position of the 5th element that violates the order of lists. When compare both lists it
returns the false.

Lists maintain the order of the element for the lifetime. That's why it is the ordered
collection of objects.

1. a = [1, 2,"Peter", 4.50,"Ricky",5, 6]


2. b = [1, 2,"Peter", 4.50,"Ricky",5, 6]
3. a == b

Output:

True

List indexing and splitting


The indexing is processed in the same way as it happens with the strings. The elements of
the list can be accessed by using the slice operator [].
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.

Jain College of BBA BCA & Commerce, Belagavi


Page 2
Python Second Chapter Notes-GSM

We can get the sub-list of the list using the following syntax.

1. list_varible(start:stop:step)
o The start denotes the starting index position of the list.
o The stop denotes the last index position of the list.
o The step is used to skip the nth element within a start:stop

Consider the following example:

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])

Jain College of BBA BCA & Commerce, Belagavi


Page 3
Python Second Chapter Notes-GSM

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]

Unlike other languages, Python provides the flexibility to use the negative indexing also.
The negative indices are counted from the right. The last element (rightmost) of the list has
the index -1; its adjacent left element is present at the index -2 and so on until the left-most
elements are encountered.

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

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

Output:

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

Jain College of BBA BCA & Commerce, Belagavi


Page 4
Python Second Chapter Notes-GSM

As we discussed above, we can get an element by using negative indexing. In the above
code, the first print statement returned the rightmost element of the list. The second print
statement returned the sub-list, and so on.

Updating List values

Lists are the most versatile data structures in Python since they are mutable, and their
values can be updated by using the slice and assignment operator.

Python also provides append() and insert() methods, which can be used to add values to
the list.

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

1. list = [1, 2, 3, 4, 5, 6]
2. print(list)
3. # It will assign value to the value to the 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]

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.

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

Jain College of BBA BCA & Commerce, Belagavi


Page 5
Python Second Chapter Notes-GSM

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.

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

1. Consider a Lists l1 = [1, 2, 3, 4], and l2 = [5, 6, 7, 8] to perform operation.

Operator Description Example

Repetition The repetition operator enables the list L1*2 = [1, 2, 3, 4, 1, 2,


elements to be repeated multiple times. 3, 4]

Concatenation It concatenates the list mentioned on l1+l2 = [1, 2, 3, 4, 5, 6,


either side of the operator. 7, 8]

Membership It returns true if a particular item exists print(2 in l1) prints


in a particular list otherwise false. True.

Iteration The for loop is used to iterate over the for i in l1:
list elements. print(i)
Output
1
2

Jain College of BBA BCA & Commerce, Belagavi


Page 6
Python Second Chapter Notes-GSM

3
4

Length It is used to get the length of the list len(l1) = 4

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.

1. list = ["John", "David", "James", "Jonathan"]


2. for i in list:
3. # The i variable will iterate over the elements of the List and contains each element in eac
h iteration.
4. print(i)

Output:

John
David
James
Jonathan

Adding elements to the list

Python provides append() function which is used to add an element to the list. However,
the append() function can only add value to the end of the list.

Consider the following example in which, we are taking the elements of the list from the
user and printing the list on the console.

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:"))

Jain College of BBA BCA & Commerce, Belagavi


Page 7
Python Second Chapter Notes-GSM

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:5


Enter the item:25
Enter the item:46
Enter the item:12
Enter the item:75
Enter the item:42
printing the list items
25 46 12 75 42

Removing elements from the list

Python provides the remove() function which is used to remove the element from the list.
Consider the following example to understand this concept.

Example -

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

Jain College of BBA BCA & Commerce, Belagavi


Page 8
Python Second Chapter Notes-GSM

Python List Built-in functions

SN Function Description Example

1 cmp(list1, list2) It compares the This method is not used in the


elements of both Python 3 and the above
the lists. versions.

2 len(list) It is used to L1 = [1,2,3,4,5,6,7,8]


calculate the print(len(L1))
length of the list. 8

3 max(list) It returns the L1 = [12,34,26,48,72]


maximum print(max(L1))
element of the 72
list.

4 min(list) It returns the L1 = [12,34,26,48,72]


minimum print(min(L1))
element of the 12
list.

5 list(seq) It converts any str = "Johnson"


sequence to the s = list(str)
list. print(type(s))
<class list>
Python provides the following built-in functions, which can be used with the lists.

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

Example: 1- Write the program to remove the duplicate element of the list.

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:

Jain College of BBA BCA & Commerce, Belagavi


Page 9
Python Second Chapter Notes-GSM

6. list2.append(i)
7. print(list2)

Output:

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

Example:2- Write a program to find the sum of the element in the list.

1. list1 = [3,4,5,9,10,12,24]
2. sum = 0
3. for i in list1:
4. sum = sum+i
5. print("The sum is:",sum)

Output:

The sum is: 67

Example: 3- Write the program to find the lists consist of at least one common element.

1. list1 = [1,2,3,4,5,6]
2. list2 = [7,8,9,2,10]
3. for x in list1:
4. for y in list2:
5. if x == y:
6. print("The common element is:",x)

Output:

The common element is: 2

Jain College of BBA BCA & Commerce, Belagavi


Page 10
Python Second Chapter Notes-GSM

Python Tuple

Python Tuple is used to store the sequence of immutable Python objects. The tuple is
similar to lists since the value of the items stored in the list can be changed, whereas the
tuple is immutable, and the value of the items stored in the tuple cannot be changed.

Creating a tuple

A tuple can be written as the collection of comma-separated (,) values enclosed with the
small () brackets. The parentheses are optional but it is good practice to use. A tuple can be
defined as follows.

1. T1 = (101, "Peter", 22)


2. T2 = ("Apple", "Banana", "Orange")
3. T3 = 10,20,30,40,50
4.
5. print(type(T1))
6. print(type(T2))
7. print(type(T3))

Output:

<class 'tuple'>
<class 'tuple'>
<class 'tuple'>
Note: The tuple which is created without using parentheses is also known as tuple packing.

An empty tuple can be created as follows.

T4 = ()

Creating a tuple with single element is slightly different. We will need to put comma after
the element to declare the tuple.

1. tup1 = ("JavaTpoint")
2. print(type(tup1))
3. #Creating a tuple with single element
4. tup2 = ("JavaTpoint",)

Jain College of BBA BCA & Commerce, Belagavi


Page 11
Python Second Chapter Notes-GSM

5. print(type(tup2))

Output:

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

A tuple is indexed in the same way as the lists. The items in the tuple can be accessed by
using their specific index value.

Consider the following example of tuple:

Example - 1
1. tuple1 = (10, 20, 30, 40, 50, 60)
2. print(tuple1)
3. count = 0
4. for i in tuple1:
5. print("tuple1[%d] = %d"%(count, i))
6. count = count+1

Output:

(10, 20, 30, 40, 50, 60)


tuple1[0] = 10
tuple1[1] = 20
tuple1[2] = 30
tuple1[3] = 40
tuple1[4] = 50
tuple1[5] = 60

Example - 2
1. tuple1 = tuple(input("Enter the tuple elements ..."))
2. print(tuple1)
3. count = 0
4. for i in tuple1:
5. print("tuple1[%d] = %s"%(count, i))
6. count = count+1

Output:

Enter the tuple elements ...123456


('1', '2', '3', '4', '5', '6')
tuple1[0] = 1

Jain College of BBA BCA & Commerce, Belagavi


Page 12
Python Second Chapter Notes-GSM

tuple1[1] = 2
tuple1[2] = 3
tuple1[3] = 4
tuple1[4] = 5
tuple1[5] = 6

A tuple is indexed in the same way as the lists. The items in the tuple can be accessed by
using their specific index value.

We will see all these aspects of tuple in this section of the tutorial.

Tuple indexing and slicing

The indexing and slicing in the tuple are similar to lists. 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 index [] operator. Python also allows us
to use the colon operator to access multiple items in the tuple.

Consider the following image to understand the indexing and slicing in detail.

Jain College of BBA BCA & Commerce, Belagavi


Page 13
Python Second Chapter Notes-GSM

Consider the following example:

1. tup = (1,2,3,4,5,6,7)
2. print(tup[0])
3. print(tup[1])
4. print(tup[2])
5. # It will give the IndexError
6. print(tup[8])

Output:

1
2
3
tuple index out of range

In the above code, the tuple has 7 elements which denote 0 to 6. We tried to access an
element outside of tuple that raised an IndexError.

1. tuple = (1,2,3,4,5,6,7)
2. #element 1 to end
3. print(tuple[1:])
4. #element 0 to 3 element
5. print(tuple[:4])
6. #element 1 to 4 element
7. print(tuple[1:5])
8. # element 0 to 6 and take step of 2
9. print(tuple[0:6:2])

Output:

(2, 3, 4, 5, 6, 7)
(1, 2, 3, 4)
(1, 2, 3, 4)
(1, 3, 5)

Negative Indexing

The tuple element can also access by using negative indexing. The index of -1 denotes the
rightmost element and -2 to the second last item and so on.

Jain College of BBA BCA & Commerce, Belagavi


Page 14
Python Second Chapter Notes-GSM

The elements from left to right are traversed using the negative indexing. Consider the
following example:

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

Output:

5
2
(3, 4)
(1, 2, 3, 4)
(4, 5)

Deleting Tuple

Unlike lists, the tuple items cannot 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.

1. tuple1 = (1, 2, 3, 4, 5, 6)
2. print(tuple1)
3. del tuple1[0]
4. print(tuple1)
5. del tuple1
6. 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

Basic Tuple operations

Jain College of BBA BCA & Commerce, Belagavi


Page 15
Python Second Chapter Notes-GSM

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.

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,


elements to be repeated multiple times. 1, 2, 3, 4, 5)

Concatenation It concatenates the tuple mentioned on either T1+T2 = (1, 2, 3, 4,


side of the operator. 5, 6, 7, 8, 9)

Membership It returns true if a particular item exists in the print (2 in T1)


tuple otherwise false prints True.

Iteration The for loop is used to iterate over the tuple for i in T1:
elements. print(i)
Output

1
2
3
4
5

Length It is used to get the length of the tuple. len(T1) = 5

Python Tuple inbuilt functions

Jain College of BBA BCA & Commerce, Belagavi


Page 16
Python Second Chapter Notes-GSM

SN Function Description

1 cmp(tuple1, tuple2) It compares two tuples and returns true if


tuple1 is greater than tuple2 otherwise
false.

2 len(tuple) It calculates the length of the tuple.

3 max(tuple) It returns the maximum element of the


tuple

4 min(tuple) It returns the minimum element of the


tuple.

5 tuple(seq) It converts the specified sequence to the


tuple.

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 a dictionary without keys. Consider the following nested structure,
which can be used as a dictionary.

1. [(101, "John", 22), (102, "Mike", 28), (103, "Dustin", 30)]

Jain College of BBA BCA & Commerce, Belagavi


Page 17
Python Second Chapter Notes-GSM

Python Dictionary
Python Dictionary is used to store the data in a key-value pair format. The dictionary is the
data type in Python, which can simulate the real-life data arrangement where some specific
value exists for some particular key. It is the mutable data-structure. The dictionary is
defined into element Keys and values.

o Keys must be a single element


o Value can be any type such as list, tuple, integer, etc.

In other words, we can say that a dictionary is the collection of key-value pairs where the
value can be any Python object. In contrast, the keys are the immutable Python object, i.e.,
Numbers, string, or tuple.

Creating the dictionary

The dictionary can be created by using multiple key-value pairs enclosed with the curly
brackets {}, and each key is separated from its value by the colon (:).The syntax to define
the dictionary is given below.

Syntax:

1. Dict = {"Name": "Tom", "Age": 22}

In the above dictionary Dict, The keys Name and Age are the string that is an immutable
object.

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

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


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

Output

<class 'dict'>
Printing Employee data ....
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}

Jain College of BBA BCA & Commerce, Belagavi


Page 18
Python Second Chapter Notes-GSM

Python provides the built-in function dict() method which is also used to create dictionary.
The empty curly braces {} is used to create empty dictionary.

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: 'Java', 2: 'T', 3:'Point'})
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([(1, 'Devansh'), (2, 'Sharma')])
15. print("\nDictionary with each item as a pair: ")
16. print(Dict)

Output:

Empty Dictionary:
{}

Create Dictionary by using dict():


{1: 'Java', 2: 'T', 3: 'Point'}

Dictionary with each item as a pair:


{1: 'Devansh', 2: 'Sharma'}

Accessing the dictionary values

We have discussed how the data can be accessed in the list and tuple by using the indexing.

However, the values can be accessed in the dictionary by using the keys as keys are unique
in the dictionary.

The dictionary values can be accessed in the following way.

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


2. print(type(Employee))

Jain College of BBA BCA & Commerce, Belagavi


Page 19
Python Second Chapter Notes-GSM

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:

<class 'dict'>
printing Employee data ....
Name : John
Age : 29
Salary : 25000
Company : GOOGLE

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 its values can be updated by using the specific
keys. The value can be updated along with key Dict[key] = value. The update() method is
also used to update an existing value.

Note: If the key-value already present in the dictionary, the value gets updated. Otherwise,
the new keys added in the dictionary.

Let's see an example to update the dictionary values.

Example - 1:

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)

Jain College of BBA BCA & Commerce, Belagavi


Page 20
Python Second Chapter Notes-GSM

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:

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


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:
Jain College of BBA BCA & Commerce, Belagavi
Page 21
Python Second Chapter Notes-GSM

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)}

Deleting elements using del keyword

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

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


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': 'John', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}
Deleting some of the employee data
printing the modified information
{'Age': 29, 'salary': 25000}
Deleting the dictionary: Employee
Lets try to print it again
NameError: name 'Employee' is not defined

Jain College of BBA BCA & Commerce, Belagavi


Page 22
Python Second Chapter Notes-GSM

The last print statement in the above code, it raised an error because we tried to print the
Employee dictionary that already deleted.

o Using pop() method

The pop() method accepts the key as an argument and remove the associated value.
Consider the following example.

1. # Creating a Dictionary
2. Dict = {1: 'JavaTpoint', 2: 'Peter', 3: 'Thomas'}
3. # Deleting a key
4. # using pop() method
5. pop_ele = Dict.pop(3)
6. print(Dict)

Output:

{1: 'JavaTpoint', 2: 'Peter'}

Python also provides a built-in methods popitem() and clear() method for remove
elements from the dictionary. The popitem() removes the arbitrary element from a
dictionary, whereas the clear() method removes all elements to the whole dictionary.

Iterating Dictionary

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

Example 1

# for loop to print all the keys of a dictionary

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


2. for x in Employee:
3. print(x)

Output:

Name
Age
salary
Company

Jain College of BBA BCA & Commerce, Belagavi


Page 23
Python Second Chapter Notes-GSM

Example 2

#for loop to print all the values of the dictionary

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


2. for x in Employee:
3. print(Employee[x])

Output:

John
29
25000
GOOGLE

Example - 3

#for loop to print the values of the dictionary by using values() method.

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


2. for x in Employee.values():
3. print(x)

Output:

John
29
25000
GOOGLE

Example 4

#for loop to print the items of the dictionary by using items() method.

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


2. for x in Employee.items():
3. print(x)

Output:

('Name', 'John')
('Age', 29)
('salary', 25000)
('Company', 'GOOGLE')
Jain College of BBA BCA & Commerce, Belagavi
Page 24
Python Second Chapter Notes-GSM

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.

1. Employee={"Name":"John","Age":29,"Salary":25000,"Company":"GOOGLE","Name":"John"}

2. for x,y in Employee.items():


3. print(x,y)

Output:

Name John
Age 29
Salary 25000
Company GOOGLE

2. In python, the key cannot be any mutable object. We can use numbers, strings, or tuples
as the key, but we cannot use any mutable object like the list as the key in the dictionary.

Consider the following example.

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE",[100,201,30


1]:"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":25000,"Company":"GOOGLE",[100,201,301]:"Department ID"}
TypeError: unhashable type: 'list'

Built-in Dictionary functions

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

Jain College of BBA BCA & Commerce, Belagavi


Page 25
Python Second Chapter Notes-GSM

SN Function Description

1 cmp(dict1, dict2) It compares the items of both the dictionary and returns
true if the 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.

Built-in Dictionary methods

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

SN Method Description

1 dic.clear() It is used to delete all the items of the


dictionary.

2 dict.copy() It returns a shallow copy of the dictionary.

3 dict.fromkeys(iterable, Create a new dictionary from the iterable with


value = None, /) the values equal to value.

4 dict.get(key, default = It is used to get the value specified for the


"None") passed key.

5 dict.has_key(key) It returns true if the dictionary contains the

Jain College of BBA BCA & Commerce, Belagavi


Page 26
Python Second Chapter Notes-GSM

specified key.

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

7 dict.keys() It returns all the keys of the dictionary.

8 dict.setdefault(key,default= It is used to set the key to the default value if


"None") the key is not specified in the dictionary

9 dict.update(dict2) It updates the dictionary by adding the key-


value pair of dict2 to this dictionary.

10 dict.values() It returns all the values of the dictionary.

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", "Saturday", "Sunday"}
2. print(Days)
3. print(type(Days))
4. print("looping through the set elements ... ")
Jain College of BBA BCA & Commerce, Belagavi
Page 27
Python Second Chapter Notes-GSM

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", "Saturday", "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

Jain College of BBA BCA & Commerce, Belagavi


Page 28
Python Second Chapter Notes-GSM

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.

Jain College of BBA BCA & Commerce, Belagavi


Page 29
Python Second Chapter Notes-GSM

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 ...

Jain College of BBA BCA & Commerce, Belagavi


Page 30
Python Second Chapter Notes-GSM

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.

Jain College of BBA BCA & Commerce, Belagavi


Page 31
Python Second Chapter Notes-GSM

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...");

Jain College of BBA BCA & Commerce, Belagavi


Page 32
Python Second Chapter Notes-GSM

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.

Jain College of BBA BCA & Commerce, Belagavi


Page 33
Python Second Chapter Notes-GSM

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()

Jain College of BBA BCA & Commerce, Belagavi


Page 34
Python Second Chapter Notes-GSM

Jain College of BBA BCA & Commerce, Belagavi


Page 35
Python Second Chapter Notes-GSM

Jain College of BBA BCA & Commerce, Belagavi


Page 36

You might also like