Python Unit 3
Python Unit 3
1. LISTS,
2. DICTIONARIES,
3. TUPLES AND
4. SETS
LISTS DICTIONARIES TUPLES SETS
• Mutable: lists are mutable, meaning we can change their values after they
are created.
• Ordered: lists maintains the order in which the elements were added to it.
• Indexing: we can access the elements of a list by their index.
• Slicing: we can extract a subset of elements from a list using slicing which
uses colon to separate a start and end indices.
Creating lists: different ways to create a list in python
1. Using square brackets: we can create a list by enclosing a comma-
separated sequence of values inside square brackets.
For example: my_list = [1, 2, 3, 4, 5]
2. Slicing: we can create a new list that contains a subset of the items in the
original list by using slicing. Slicing uses a colon to separate the start and stop
value. Example:
my_list = [1, 2, 3, 4, 5]
print(my_list[1:4]) #[2, 3, 4]
Operations on Lists:
3. Concatenation: we can combine 2 or more lists into a single list using
concatenation, which uses + operator. Example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
concatenated_list = list1 + list2
print(concatenated_list) # [1, 2, 3, 4, 5, 6]
4. Repetition: we can create a new list that contains multiple copies of the
items in the original list using repetition, which uses * operator. Example:
my_list = [1, 2, 3]
repeated_list = my_list * 3
print(repeated_list) #[1, 1, 1, 2, 2, 2, 3, 3, 3]
Operations on Lists:
5. Length: we can determine the number of items in a list using the len()
function. Example:
mylist = [1, 2, 3, 5, 7]
print(len(mylist)) #5
8. Reversing: we can reverse the order of items in a list using the reverse() method.
Example:
my_list = [1, 2, 3]
my_list.reverse()
print(my_list) # [3, 2, 1]
Built-in Functions on Lists:
1. len() 8. count()
2. max() 9. index()
3. min() 10. append()
4. sum() 11. extend()
5. sorted() 12. insert()
6. reversed() 13. remove()
7. list() 14. pop()
15. clear()
Built-in Functions on Lists:
1. len(): This function returns the number of items in a list. Example:
my_list = [1, 3, 2]
print(len(my_list)) #3
4. sum(): This function returns the sum of all the elements in a list. Example:
my_list = [1, 3, 2]
print(sum(my_list)) #3
5. list(): Using list() function, we can convert a sequence (tuple, string) into list.
Example:
tuple = (1, 2, 3, 4)
my_list = list(tuple)
print(my_list) # [1, 2, 3, 4]
Built-in Functions on Lists:
6. sorted(): This function returns a sorted order of list in ascending order.
Example:
my_list = [3, 1, 2]
sorted_list = sorted(my_list)
print(sorted_list)) # [1, 2, 3]
11. extend(e): This function adds the elements of another list to the end of the
list. Example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # [1, 2, 3, 4, 5, 6]
Built-in Functions on Lists:
12. insert(i,e): This function inserts an element at a specified position in the
list. Example:
my_list = [1, 2, 3, 4]
my_list.insert(0, 5)
print(my_list) # [5, 1, 2, 3, 4]
13. remove(e): This function removes the first occurrence of a specified
element in the list. Example:
numbers = [50, 10, 20, 30, 40, 50]
numbers.remove(30)
print(numbers) # [50, 10, 20, 40, 50]
numbers.remove(50)
print(numbers) # [10, 20, 40, 50]
Built-in Functions on Lists:
14. pop(): Using this function element can be removed from the list by specifying the
index value. If the indexed item is not specified then the last item will be deleted
from the list . Example:
my_list = [11, 12, 13, 14, 15]
removed_element = my_list.pop(1)
print(removed_element) # 12
removed_element = my_list.pop()
print(removed_element) # 15
15. clear(): This function removes all the elements from list. Example:
my_list = [1, 3, 2, 5, 7]
my_list.clear()
print(my_list) #[]
Nested Lists:
A Nested list is a list that contains another list as its elements. The elements of
a nested list can be accessed using multiple indices.
my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
In this example, my_list is a list that contains three other lists as its
elements. The first element is [1, 2, 3], the second element is [4, 5, 6] and last
element is [7, 8, 9].
We can access the elements of a nested list using multiple indices. For
example,
my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(my_list[0][0]) #1
print(my_list[1][2]) #6
print(my_list[2]) # [7, 8, 9]
DICTIONARIES
• Creating Dictionaries;
• Operations on Dictionaries;
• Built-in Functions on Dictionaries;
• Dictionary Methods;
• Populating and Traversing Dictionaries.
DICTIONARIES
• Creating dictionaries:
print("Age:", Employee["Age"])
print("Salary:", Employee["salary"])
print("Company:", Employee["Company"])
1. # Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
Dict[3] = ‘Rocky'
print("Dictionary after updating: ")
print(Dict)
Dict = {}
print("Empty Dictionary: ")
print(Dict)
del Employee
print(Employee)
Checking for existence of keys in Dictionary
• We use in keyword check existence of key in the dictionary.
• For example,
del Employee["Name"]
print(“Name” in Employee)
Looping over keys or values in dictionary
• We can loop through in dictionary for keys or values.
• For example,
2. keys()
3. values()
4. items()
5. get()
6. pop()
7. sorted()
Dictionary Methods
1. clear()
2. copy()
3. update()
4. pop()
5. popitem()
6. get()
7. items()
8. keys()
Dictionary Methods
1. clear() : It removes all the key-value pairs from the dictionary.
print(Emp.clear())
#{}
# None
Dictionary Methods
2. copy() : It returns a shallow copy of the dictionary.
Emp1.update(Emp2)
print(Emp1)
print(Emp1)
# 45000
# {'Name': 'Dev', 'Age': 20, 'Company': 'WIPRO'}
Dictionary Methods
5. popitem() : It removes the item (key-value pair) inserted into the dictionary.
The removed item is the return value of the popitem() method, as a tuple.
Emp1 = {"Name": "Dev", "Age": 20, “Salary":45000, "Company":"WIPRO"}
print(Emp1.popitem())
print(Emp1)
# ('Company', 'WIPRO')
# {'Name': 'Dev', 'Age': 20, 'Salary': 45000}
Dictionary Methods
6. get() : It returns the value of the specified key. If the key does not exist, it
returns the specified default value (None).
Emp1 = {"Name": "Dev", "Age": 20, “Salary":45000, "Company":"WIPRO"}
print(Emp1.get(“Age”))
# 20
Dictionary Methods
7. items() : It returns a list of all the key-value pairs in a dictionary as tuples.
for i in Employee:
print(i)
for i in Employee:
print(Employee[i])
for i in Employee.keys():
print(i)
for i in Employee.values():
print(i)
print(Employee.keys())
print(Employee.values())
TUPLES
• Creating Tuples;
• Operations on Tuples;
• Built-in Functions on Tuples;
• Tuple Methods.
Tuples
• A Tuple is an ordered collection of elements, similar to a list. However tuples
are immutable, meaning that their values cannot be changed once they are
created.
• Tuple elements are enclosed within parentheses and separated by commas.
• A tuple in Python is similar to a list. The difference between the two is that
we cannot change the elements of a tuple once it is assigned whereas we
can change the elements of a list.
Creating a Tuple
• A Tuple is created by placing all the items (elements) inside parentheses (),
separated by commas. The parentheses are optional, however, it is a good
practice to use them.
• A tuple can have any number of items and they may be of different types
(integer, float, list, string, etc.).
# prints - a
Operations on Tuples
2. Negative Indexing: Python allows negative indexing for its sequences. The
index of -1 refers to the last item, -2 to the second last item and so on. For
example;
6. Length: We can find the length of a tuple using the len() function. For
example;
letters1 = ('p', ‘y', ‘t', ‘h', ‘o', ‘n')
print(len(letters1))
#6
Operations on Tuples
7. Membership test: We can check if an element is present in a tuple using the
in operator. For example;
my_tuple = ('p', ‘y', ‘t', ‘h', ‘o', ‘n')
print( ‘p’ in my_tuple) #True
print( ‘g’ in my_tuple) #False
8. Iteration: We can iterate over the elements of a tuple using a for loop. For
example;
letters1 = ('p', ‘y', ‘t', ‘h', ‘o', ‘n')
p
for elements in letters1: y
t
print(elements) h
o
n
Built-in Functions on Tuples
• len()
• max()
• min()
• sum()
• sorted()
Built-in Functions on Tuples
• len() – returns the number of elements in a tuple.
print(len(my_tuple)) #6
print(max(my_tuple)) #6
print(min(my_tuple)) #1
print(sum(my_tuple)) # 21
print(sorted(my_tuple)) # [1, 2, 3, 4, 5, 6]
Tuple Methods
• Tuples are immutable in Python, which means they cannot be modified once
they are created. As a result, there are only two methods defined for tuples;
1. count()
2. index()
• 1. count(): This method takes one argument and returns the number of
times that argument appears in the tuple:
Example: my_tuple = (1, 2, 3, 4, 5, 1, 2, 1, 1)
print(my_tulpe(count(1))
#4
Tuple Methods
• 2. index(): This method takes one argument and returns the index of the
first occurrence of that argument in the tuple. If the argument is not found,
it raises ValueError.
Example: my_tuple = (1, 2, 3, 4, 5, 1, 2, 1, 1)
print(my_tulpe(index(4)) #3
print(my_tulpe(index(1)) #0
Note: These methods do not modify the original tuple. If you wish to modify a
tuple, you must first convert it to a list, make changes and then convert it back
to a tuple.
SETS
• Creating Sets;
• Operations on Sets;
• Built-in Functions on Sets;
• Set Methods.
Sets
• A set is an unordered collection of unique elements. In other words, Python
Set is a collection of elements (objects) that contains no duplicate elements.
• Sets are enclosed in curly braces { }.
• The set data type is mutable, which means we can add or remove elements
from it.
• A set is a collection which is unordered, unchangeable, and unindexed.
• Sets are unordered, i.e we cannot access elements by index value
(unindexed). Instead, we can iterate over the set using a loop or we can use
the in operator to check if an element is present in the set.
• Set items are unchangeable, but you can remove items and add new items.
• Sets do not allow duplicate elements. If you try to add a duplicate element to
a set, it will be ignored.
Creating Sets
• In Python, we create sets by placing all the elements inside curly braces {},
separated by comma and also set can be created using the set() function.
• A set can have any number of items and they may be of different types
(integer, float, tuple, string etc.). But a set cannot have mutable elements like
lists, sets or dictionaries as its elements.
Creating Sets: Example
#1 create a set of integer type
• student_id = {112, 114, 116, 118, 115}
• print('Student ID:', student_id)
Note:
#2 create a set of string type When you run this code, you might
get output in a different order.
• vowel_letters = {'a', 'e', 'i', 'o', 'u'} This is because the set has no
particular order.
• print('Vowel Letters:', vowel_letters)
# Note: the set list is unordered, so the result will display the items in a random
order.
# Output: 3
Built-in Functions on Sets
• max(): The max() function returns the largest item in an iterable. It can also
be used to find the largest item between 2 or more parameters.
• Example:
numbers = {9, 34, 11, -4, 27}
max_number = max(numbers)
print(max_number)
# Output: 34
Built-in Functions on Sets
• min(): The min() function returns the smallest item in an iterable. It can also
be used to find the smallest item between 2 or more parameters.
• Example:
numbers = {9, 34, 11, -4, 27}
min_number = min(numbers)
print(min_number)
# Output: -4
Built-in Functions on Sets
• sum(): The sum() function adds the items of an iterable and returns the sum.
• Example:
marks = {65, 71, 68, 74, 61}
total_marks = sum(marks)
print(total_marks)
# Output: 339
Built-in Functions on Sets
• sorted(): The sorted() function sorts the elements of a given iterable in a
specific order (ascending or descending) and returns it as a list.
• Example:
numbers = {65, 71, 68, 74, 61}
sorted_nos = sorted(numbers) reverse=True
print(sorted_nos)
4. difference() method: computes the difference of two sets and returns items
that are unique to the first set.
numbers1 = {1, 3, 5, 7, 9}
numbers2 = {2, 3, 5, 7, 11}
print(numbers.difference(numbers2)) # Output: {1, 9}
5. difference_update() method: computes the difference between two sets (A -
B) and updates set A with the resulting set.
• Example:
nos1 = {1, 3, 5, 7, 9}
nos2 = {2, 3, 5, 7, 11}
nos1.difference_update(nos2)
print(nos1) # Output: {1, 9}
6. pop () method: randomly removes an item from a set and returns the
removed item.
• Example:
A = {‘a’, ‘b’, ‘c’, ‘d’}
removed_item = A.pop()
print(removed_item) # Output: c or d or any1
7. discard() method: Removes an element from the set if it is a member. (Do
nothing if the element is not in set.)
numbers = {2, 3, 4, 5}
numbers.discard(3)
print(numbers) # Output: {2, 4, 5}