Chapter 3
Chapter 3
1
List
Lists are just like dynamic sized arrays, declared in other languages (vector in C++
and ArrayList in Java).
Lists need not be homogeneous always which makes it a most powerful tool in Python.
A single list may contain DataTypes like Integers, Strings, as well as Objects.
Lists are mutable, and hence, they can be altered even after their
List in Python are ordered and have a definite count. The elements in a list are indexed
according to a definite sequence and the indexing of a list is done with 0 being the first
index.
Each element in the list has its definite place in the list, which allows duplicating of
elements in the list, with each element having its own distinct place and credibility.
-
2
Creating a List
Lists in Python can be created by just placing the sequence inside the square brackets[].
list doesn’t need a built-in function for creation of list.
# Creating a List
List = [] Output
print("Blank List: ") Blank List:
[]
print(List)
List of numbers:
# Creating a List of numbers [10, 20, 14]
List = [10, 20, 14]
print("\nList of numbers: ")
print(List)
3
Accessing Values in Lists
To access values in lists, use the square brackets for slicing along with the index or
indices to obtain value available at that index. For example −
#!/usr/bin/python3
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7 ]
4
# Creating a List of strings and numbers and
accessing
# using index Output:
List = ["a", "10", "12.7"]
print("\nList Items: ") List Items:
print(List[0]) a
print(List[2]) 12.7
#!/usr/bin/python3
list[2] = 2001
print ("New value available at index 2 : ", list[2])
7
Delete List Elements
To remove a list element, you can use either the del statement if you know exactly which
element(s) you are deleting. You can use the remove() method if you do not know
exactly which items to delete. For example −
#!/usr/bin/python3
del list[2]
print ("After deleting value at index 2 : ", list)
8
Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"] Output
thislist.append("orange") ['apple', 'banana', 'cherry', 'orange']
print(thislist)
9
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of
the current list
index() Returns the index of the first element with the specified
value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
13
Sr. Function with Description
No
.
1 cmp(tuple1,tuple2):Compares elements of both
tuples.
2 len(tuple): Gives the total length of the tuple.
3 max(tuple): Returns item from the tuple with max
value.
4 min(tuple): Returns item from the tuple with min
value.
14
Dictionary
Each key is separated from its value by a colon (:), the items are separated by
commas, and the whole thing is enclosed in curly braces. An empty dictionary without
any items is written with just two curly braces, like this: {}.
Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionaries are changeable, meaning that we can change, add or remove items after
the dictionary has been created.
Keys are unique within a dictionary while values may not be. The values of a
dictionary can be of any type, but the keys must be of an immutable data type such
as strings, numbers, or tuples.
Duplicates Not Allowed: Dictionaries cannot have two items with the same key
15
Create:
Output
dict={} {}
print(dict) {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print(dict)
# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
# KeyError
print(my_dict['address']) 17
Changing and Adding Dictionary elements
Dictionaries are mutable. We can add new items or change the value of existing items using
an assignment operator
If the key is already present, then the existing value gets updated. In case the key is not
present, a new (key: value) pair is added to the dictionary.
# Changing and adding Dictionary Elements
my_dict = {'name': 'Jack', 'age': 26}
# update value
my_dict['age'] = 27
#Output: {'age': 27, 'name': 'Jack'}
print(my_dict)
# add item
my_dict['address'] = 'Downtown'
# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'} 18
print(my_dict)
Removing elements from Dictionary
We can remove a particular item in a dictionary by using the pop() method This method
removes an item with the provided key and returns the value.
The popitem() method can be used to remove and return an arbitrary (key,value) item pair
from the dictionary. All the items can be removed at once, using the clear()
We can also use the del keyword to remove individual items or the entire dictionary itself.
19
# Removing elements from a dictionary
# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# remove a particular item, returns its value
# Output: 16
print(squares.pop(4))
# Output: {1: 1, 2: 4, 3: 9, 5: 25}
print(squares)
# remove an arbitrary item, return (key,value)
# Output: (5, 25)
print(squares.popitem())
# Output: {1: 1, 2: 4, 3: 9}
print(squares)
# remove all items
squares.clear()
# Output: {}
print(squares)
# delete the dictionary itself
del squares
# Throws Error 20
print(squares)
Dictionary Methods
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert
the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary 21
Set
• Mathematically a set is a collection of items not in any particular
order. A Python set is similar to this mathematical definition with
below additional conditions.
• The elements in the set cannot be duplicates.
• The elements in the set are immutable(cannot be modified) but the
set as a whole is mutable.
• There is no index attached to any element in a python set. So they
do not support any indexing or slicing operation.
22
Creating a set
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]
)
Months={"Jan","Feb","Mar"}
Dates={21,22,17} print(Days)
print(Months) 23
print(Dates)
Accessing Values in a Set
24
Adding Items to a Set
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])
Days.add("Sun")
print(Days)
25
Removing Item from a Set
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])
Days.discard("Sun")
print(Days)
26
Union of Sets
• The union operation on two sets produces a new set containing all
the distinct elements from both the sets. In the below example the
element “Wed” is present in both the sets.
DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA|DaysB
print(AllDays)
27
Intersection of Sets
• The intersection operation on two sets produces a new set containing
only the common elements from both the sets. In the below example
the element “Wed” is present in both the sets.
DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA & DaysB
print(AllDays)
28
Difference of Sets
• The difference operation on two sets produces a new set containing
only the elements from the first set and none from the second set. In
the below example the element “Wed” is present in both the sets so
it will not be found in the result set.
DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA - DaysB
print(AllDays)
29
Compare Sets
• We can check if a given set is a subset or superset of another set.
The result is True or False depending on the elements present in the
sets.
DaysA= set(["Mon","Tue","Wed"])
DaysB = set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
SubsetRes = DaysA <= DaysB
SupersetRes = DaysB >= DaysA
print(SubsetRes)
print(SupersetRes)
30