Module 3
Lists: Creation, Indexing, Slicing, List operations, Aliasing, Cloning lists, Lists and for loops,
List comprehensions, List handling methods and Applications
Tuples: Properties, Creation, Packing/Unpacking, and Applications.
Dictionaries: Key-value operations, Iteration, Dictionary comprehension, Dictionary
methods and Applications.
Sets: Set creation, operations, and set comprehension.
By
Prof Mahalaxmi S Bellubbi
CSE Dept.
List
• A list is a built-in data structure that can hold an ordered collection of
items. Unlike arrays in some languages, Python lists are very flexible:
• Can contain duplicate items
• Mutable: items can be modified, replaced, or removed
• Ordered: maintains the order in which items are added
• Index-based: items are accessed using their position (starting from 0)
• Can store mixed data types (integers, strings, booleans, even other
lists)
Creating a List
• Lists can be created in several ways, such as using square brackets,
the list() constructor or by repeating elements. Let's look at each
method one by one with example:
1. Using Square Brackets
2. Using list() Constructor
3. Creating List with Repeated Elements
1. Using Square Brackets
We use square brackets [] to create a list directly.
a = [1, 2, 3, 4, 5] # List of integers
b = ['apple', 'banana', 'cherry'] # List of strings
c = [1, 'hello', 3.14, True] # Mixed data types
print(a)
print(b)
print(c)
Output:
[1, 2, 3, 4, 5]
['apple', 'banana', 'cherry']
[1, 'hello', 3.14, True]
2. Using list() Constructor
We can also create a list by passing an iterable (like a tuple, string or
another list) to the list() function.
a = list((1, 2, 3, 'apple', 4.5))
print(a)
b = list("GFG")
print(b)
Output:
[1, 2, 3, 'apple', 4.5]
['G', 'F', 'G']
3. Creating List with Repeated Elements
We can use the multiplication operator * to create a list with repeated items.
a = [2] * 5
b = [0] * 7
print(a)
print(b)
Output:
[2, 2, 2, 2, 2]
[0, 0, 0, 0, 0, 0, 0]
Read List Elements One by One (Using Loop)
n = int(input("Enter number of elements: "))
lst = []
for i in range(n):
item = input("Enter item: ")
[Link](item)
print(lst)
Output:
Enter number of elements: 4
Enter item: 4
Enter item: 3
Enter item: 2
Enter item: 1
['4', '3', '2', '1']
>>>
Accessing List Elements
Elements in a list are accessed using indexing. Python indexes start at 0, so a[0]
gives the first element. Negative indexes allow access from the end (e.g., -1 gives
the last element).
a = [10, 20, 30, 40, 50]
print(a[0])
print(a[-1])
print(a[1:4]) # elements from index 1 to 3
Output:
10
50
[20, 30, 40]
Adding Elements into List
add elements to a list using the following methods:
append(): Adds an element at the end of the list.
extend(): Adds multiple elements to the end of the list.
Output:
insert(): Adds an element at a specific position.
After append(10): [10]
clear(): removes alla = [] After insert(0, 5): [5, 10]
After extend([15, 20, 25]): [5, 10, 15, 20, 25]
[Link](10) After clear(): []
print("After append(10):", a)
[Link](0, 5)
print("After insert(0, 5):", a)
[Link]([15, 20, 25])
print("After extend([15, 20, 25]):", a)
[Link]()
print("After clear():", a) items.
Updating Elements into List
Since lists are mutable, we can update elements by accessing them via
their index.
a = [10, 20, 30, 40, 50]
a[1] = 25
print(a)
Output:
[10, 25, 30, 40, 50]
Removing Elements from List
remove elements from a list using:
remove(): Removes the first occurrence of an element.
pop(): Removes the element at a specific index or the last Output:
element if no index is specified. After remove(30): [10, 20, 40, 50]
del statement: Deletes an element at a specified index. Popped element: 20
a = [10, 20, 30, 40, 50] After pop(1): [10, 40, 50]
After del a[0]: [40, 50]
[Link](30)
print("After remove(30):", a)
popped_val = [Link](1)
print("Popped element:", popped_val)
print("After pop(1):", a)
del a[0]
print("After del a[0]:", a)
Iterating Over Lists
iterate over lists using loops, which is useful for performing actions on each item.
Example:
a = ['apple', 'banana', 'cherry']
for item in a:
print(item)
Output:
apple
banana
cherry
Indexing
• lists are ordered collections of items, and each item has a specific position or
index. Indexing allows you to access individual elements within a list using their
position.
• Key concepts for list indexing in Python:
Zero-based indexing:
Python uses zero-based indexing, meaning the first element in a list is at index 0,
the second at index 1, and so on.
Positive indexing:
You can access elements using positive integers starting from 0 for the first
element
Example:
my_list = ['apple', 'banana', 'cherry', 'date’]
print(my_list[0]) # Output: apple
print(my_list[2]) # Output: cherry
Negative indexing: You can also access elements using
negative integers, which count from the end of the
list. -1 refers to the last element, -2 to the second-to-last,
and so on.
Example:
my_list = ['apple', 'banana', 'cherry', 'date']
print(my_list[-1]) # Output: date
print(my_list[-3]) # Output: banana
Slicing in list
. • Python list slicing is a powerful and flexible way to extract specific portions of a
list. It allows you to create new lists containing a subset of elements from an
existing list without modifying the original.
• Syntax:
my_list[start:stop:step]
Parameters:
• start:
• (Optional) The index where the slice begins. If omitted, it defaults to 0 (the
beginning of the list).
•stop:
(Optional) The index where the slice ends. The element at this index is not
included in the slice. If omitted, it defaults to the end of the list
•step:
(Optional) The increment between indices in the slice. If omitted, it defaults to
1. A negative step value reverses the order of the slice.
Examples
List Operations
append()
The append() method adds elements at the end of the list. This method can only
add a single element at a time. You can use the append() method inside a loop
to add multiple elements.
Example:
myList = [1, 2, 3, 'EduCBA', 'makes learning fun!’]
[Link](4)
[Link](5)
[Link](6)
for i in range(7, 9):
[Link](i)
Output:
print(myList)
extend()
The extend() method adds more than one element at the end of the list.
Although it can add more than one element, unlike append(), it adds
them at the end of the list like append().
Example:
myList = [1, 2, 3, 'EduCBA', 'makes learning fun!’]
[Link]([4, 5, 6]) for i in range(7, 11):
[Link](i)
print(myList)
Output:
insert()
The insert() method can add an element at a given position in the list. Thus, unlike
append(), it can add elements at any position, but like append(), it can add only
one element at a time. This method takes two arguments. The first argument
specifies the position, and the second argument specifies the element to be
inserted.
Example:
myList = [1, 2, 3, 'EduCBA', 'makes learning fun!’]
[Link](3, 4)
[Link](4, 5)
[Link](5, 6)
print(myList)
Output:
remove()
The remove() method removes an element from the list. Only the first
occurrence of the same element is removed in the case of multiple
occurrences.
Example:
myList = [1, 2, 3, 'EduCBA', 'makes learning fun!’]
[Link]('makes learning fun!’)
print(myList)
Output:
[1, 2, 3, 'EduCBA']
pop()
The method pop() can remove an element from any position in the list.
The parameter supplied to this method is the element index to be
removed.
Example
myList = [1, 2, 3, 'EduCBA', 'makes learning fun!’]
[Link](3)
print(myList)
Output:
[1, 2, 3, 'makes learning fun!’]
slice
The slice operation is used to print a section of the list. The slice
operation returns a specific range of elements. It does not modify
the original list.
Example:
myList = [1, 2, 3, 'EduCBA', 'makes learning fun!’]
print(myList[:4]) # prints from beginning to end index
print(myList[2:]) # prints from start index to end of list
print(myList[2:4]) # prints from start index to end index
print(myList[:]) # prints from beginning to end of list
Output:
reverse()
You can use the reverse() operation to reverse the elements of a list.
This method modifies the original list. We use the slice operation with
negative indices to reverse a list without modifying the original.
Specifying negative indices iterates the list from the rear end to the
front end of the list.
myList = [1, 2, 3, 'EduCBA', 'makes learning fun!’]
[Link]()
Output:
len()
The len() method returns the length of the list, i.e., the number of elements
in the list.
myList = [1, 2, 3, 'EduCBA', 'makes learning fun!’]
print(len(myList))
min() & max()
The min() method returns the minimum value in the list. The max()
method returns the maximum value in the list. Both methods accept only
homogeneous lists, i.e., lists with similar elements.
Example:
myList = [1, 2, 3, 4, 5, 6, 7]
print(min(myList))
print(max(myList))
Output:
1
7
sort()
The sort method sorts the list in ascending order. You can only perform
this operation on homogeneous lists, which means lists with similar
elements.
yourList = [4, 2, 6, 5, 0, 1]
[Link]() print(yourList)
Output:
#Print All Elements of a List
lst = [10, 20, 30, 40, 50]
for item in lst:
print(item)
Output:
10
20
30
40
50
#Read List Elements From User
n = int(input("Enter number of elements: "))
lst = []
for i in range(n):
value = int(input("Enter element: "))
[Link](value)
print("List =", lst)
Output:
Enter number of elements: 3
Enter element: 10
Enter element: 20
Enter element: 30
#Sum of List Elements
numbers = [5, 10, 15, 20]
total = sum(numbers)
print("Sum =", total)
Output:
Sum = 50
#Largest Number in a List
numbers = [10, 50, 20, 90, 40]
largest = max(numbers)
print("Largest =", largest)
Output:
Largest = 90
#Smallest Number in a List
numbers = [10, 50, 20, 90, 40]
smallest = min(numbers)
print("Smallest =", smallest)
Output:
Smallest = 10
#Count Even and Odd Numbers
numbers = [1, 2, 3, 4, 5, 6]
even = 0
odd = 0
for n in numbers:
if n % 2 == 0:
even += 1
else:
odd += 1
print("Even =", even)
print("Odd =", odd)
Output:
Even = 3
Odd = 3
#Reverse a List
lst = [10, 20, 30, 40]
[Link]()
print("Reversed List =", lst)
Output:
Reversed List = [40, 30, 20, 10]
Output:
Reversed List = [40, 30, 20, 10]
#Remove Duplicates From List
lst = [1, 2, 2, 3, 4, 4, 5]
unique = list(set(lst))
print("Unique List =", unique)
Output:
Unique List = [1, 2, 3, 4, 5]
#List of Squares
squares = []
for i in range(1, 6):
[Link](i * i)
print("Squares =", squares)
Output:
Squares = [1, 4, 9, 16, 25]
#write a python program to sort a list using bubble sort
# Bubble Sort using temp variable with user input
# Read number of elements Output:
n = int(input("Enter number of elements: ")) Enter number of elements: 5
Enter element 1: 12
numbers = []
Enter element 2: 5
# Read elements from the keyboard Enter element 3: 33
for i in range(n): Enter element 4: 1
num = int(input(f"Enter element {i+1}: ")) Enter element 5: 7
Original List: [12, 5, 33, 1, 7]
[Link](num) Sorted List: [1, 5, 7, 12, 33]
print("Original List:", numbers)
# Bubble Sort Logic
for i in range(n - 1):
for j in range(n - i - 1):
if numbers[j] > numbers[j + 1]:
temp = numbers[j]
numbers[j] = numbers[j + 1]
numbers[j + 1] = temp
print("Sorted List:", numbers)
#Write a python program to search and element in a list
# Read number of elements
using linear search
n = int(input("Enter number of elements: ")) Output:
numbers = [] Enter number of elements: 5
# Read elements into the list Enter element 1: 10
for i in range(n): Enter element 2: 25
Enter element 3: 3
num = int(input(f"Enter element {i+1}: "))
Enter element 4: 19
[Link](num) Enter element 5: 8
# Read element to search Enter the element to search: 19
key = int(input("Enter the element to search: ")) Element 19 found at position 4
# Linear Search Logic
found = False
for i in range(n):
if numbers[i] == key:
print(f"Element {key} found at position {i+1}")
found = True
break
if not found:
print(f"Element {key} not found in the list.")
#Write a python program to perform binary search
n = int(input("Enter number of elements: ")) while low <= high:
numbers = [] mid = (low + high) // 2
if numbers[mid] == key:
# Read elements into the list print(f"Element {key} found at position {mid + 1}")
for i in range(n): found = True
num = int(input(f"Enter element {i+1}: ")) break
elif numbers[mid] < key:
[Link](num) low = mid + 1
# Sort the list (binary search requires sorted else:
list) high = mid - 1
[Link]() if not found:
print(f"Element {key} not found in the list.")
print("Sorted List:", numbers)
Output:
# Read the key to search Enter number of elements: 5
key = int(input("Enter the element to search: Enter element 1: 12
")) Enter element 2: 5
# Binary Search Logic Enter element 3: 33
Enter element 4: 1
low = 0 Enter element 5: 7
high = n - 1 Sorted List: [1, 5, 7, 12, 33]
found = False Enter the element to search: 7
Element 7 found at position 3
Cloning a list
• Given a list of elements, the task is to create a copy of it. Copying a list ensures
that the original list remains unchanged while we perform operations on the
duplicate. This is useful when working with mutable lists, especially nested
ones.
Example:
original = [1, 2, 3, 4]
clone = original[:] # cloning
print("Original List:", original)
print("Cloned List:", clone)
Output:
Original List: [1, 2, 3, 4]
Cloned List: [1, 2, 3, 4]
Cloning :Using copy()
Using copy()
copy() method is a built-in method in Python that creates a shallow copy of
a list. This method is simple and highly efficient for cloning a list.
Example:
a = [1, 2, 3, 4, 5]
b = [Link]()
print(b)
Output:
[1, 2, 3, 4, 5]
Cloning : Using List Slicing
This method creates a new list by slicing all elements from the original.
It’s concise and performs well.
a = [1, 2, 3, 4, 5]
b = a[:]
print(b)
Output:
[1, 2, 3, 4, 5]
Lists and for loops
• A list is a collection of items stored in a single variable.
Lists are ordered, changeable, and allow duplicate elements.
A for loop is used to access each element of a list one by one.
Example:
fruits = ["apple", "banana", "mango"]
for f in fruits:
print(f)
#write a python program to find sum of elements in a list.
numbers = [10, 20, 30, 40]
total = 0
for n in numbers:
total += n
pint("Total =", total)
Output:
Total = 100
List comprehensions
• List Comprehension offers the shortest
syntax for looping through lists: Example 2:
Syntax: names = ["ram", "sita", "gita"]
new_list = [expression for item in list if upper_names = [[Link]()
condition] for name in names]
Example 1: print(upper_names)
To print the square of a number:
numbers = [1, 2, 3, 4, 5] Output:
squares = [n*n for n in numbers] ['RAM', 'SITA', 'GITA']
print(squares)
Output:
[1,4,9,16,25]
List Handling Methods
Method Description Example
append() Adds item to end [Link](5)
insert() Adds item at position [Link](2, 10)
Adds all items of another
extend() [Link]([1,2])
list
Removes first matching
remove() [Link](10)
item
pop() Removes item by index [Link](1)
sort() Sorts ascending [Link]()
reverse() Reverses list [Link]()
count() Counts occurrences [Link](2)
index() Gives index of value [Link]("apple")
Application of lists:
[Link] Storage and Manipulation
Lists are great for holding collections of data, whether all of the same type (like all integers) or
mixed types (e.g., integers, strings). You can add, remove, and update elements easily
a = [23, 45, 12, 67, 34]
[Link](89)
[Link](45)
print(a)
Output:[23, 12, 67, 34, 89]
2. Implementing Stacks and Queues
Lists can simulate stack (LIFO) and queue (FIFO) behaviors. Stack operations use append() and
pop(), while queues may require pop(0) or [Link].
s = []
[Link]('a')
[Link]('b')
print([Link]()) Output:b
3. Iteration and Data Processing
Lists are iterable and perfect for processing data, especially in loops where you perform calculations or
transformations.
a = [1, 2, 3, 4, 5]
t = sum(a)
print(f"Total: {t}")
Output:
Total: 15
4. Dynamic Arrays
Lists can grow or shrink in size, which is useful when collecting data dynamically such as user inputs or
computation results.
s = []
for i in range(10):
[Link](i * i)
print(s)
Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
5. Storing and Processing Strings
Lists can be used to manipulate strings for tasks like tokenization, filtering, or
formatting.
s = "Subtle art of not giving a bug"
w = [Link]()
for word in w:
print([Link]())
Output:
SUBTLE
ART
OF
NOT
GIVING
A
BUG
Tuples
A tuple in Python is an immutable ordered collection of elements.
Tuples are similar to lists, but unlike lists, they cannot be changed after their creation (i.e., they
are immutable).
Tuples can hold elements of different data types.
The main characteristics of tuples are being ordered, heterogeneous and immutable.
• Properties
• Ordered
Elements have a fixed order and maintain the sequence.
• Immutable
Once created, elements cannot be changed, added, or removed.
• Allow duplicate values
Tuples can contain repeated values.
• Heterogeneous
Can store different data types (int, float, string, list, etc.)
• Indexed
Access elements using index positions like tuple[0].
• Faster than lists
Tuples are optimized for performance and memory usage.
Creating a tuple
A tuple is created by placing all the items inside parentheses (), separated by commas. A
tuple can have any number of items and they can be of different data types.
Tuples can contain elements of various data types, including other
tuples, lists, dictionaries and even functions.
Examples:
Creating a tuple
t1 = (10, 20, 30)
Creating a tuple without paranthesis
t2 = 10, 20, 30
Single-element tuple (IMPORTANT)
t3 = (10,) # comma required
Empty tuple
t4 = ()
✔ Tuple from an iterable
t5 = tuple([1, 2, 3])
Packing/unpacking tuples
• Packing means placing multiple values into a single tuple (Python does it
automatically when you separate values by commas).
Example:
t1 = 1, 2, 3 # parentheses optional
t2 = (4, 5, 6) # explicit tuple literal
t3 = "a", # single-element tuple needs trailing comma
print(t1, t2, t3)
Output:
(1, 2, 3) (4, 5, 6) ('a’,)
Note:
• Writing a, b, c produces a tuple even without parentheses.
• A single value needs a trailing comma to be a tuple: ("x",).
Unpacking tuple
Tuple unpacking is a powerful feature in Python that allows you to assign the values of a
tuple to multiple variables in a single line. This technique makes your code more readable
and efficient. In other words, It is a process where we extract values from a tuple and
assign them to variables in a single step. This feature makes working with tuples more
convenient and readable
Tuple unpacking allows assigning values from a tuple directly to variables:
Example:
a, b, c = (100, 200, 300) Output:
print(a) 100
print(b) 200
print(c) 300
Key Rules:
The number of variables on the left must match the number of elements in the tuple.
If they do not match, Python raises a ValueError.
Example: a, b = (100, 200, 300) # ValueError: too many values to unpack
Application of tuples
•Returning Multiple Values from Functions
Tuples allow functions to return more than one value at a time. Python packs these
returned values into a tuple.
•Using Tuples as Dictionary Keys
Tuples are immutable, so they can be used as keys in dictionaries, unlike lists which
cannot be used as keys.
•Storing Fixed or Constant Data
Tuples are suitable for storing data that should not change, such as coordinates, RGB
values, dates, or configuration values.
•Improved Performance
Tuples are faster and more memory-efficient than lists due to their immutability. They
are preferred in performance-critical applications.
•Data Integrity
Since tuples cannot be modified after creation, they help in maintaining data integrity
and preventing accidental changes.
•Unpacking of Values
Tuples support easy unpacking, allowing grouped data to be split into
individual variables conveniently.
•Storing Records
Tuples are often used to represent simple records or structured data
items, such as database rows or student details.
•Function Arguments (*args)
Variable-length function arguments are internally handled as tuples,
making them suitable for collecting multiple inputs.
•Using Tuples in Sets
Tuples can be elements of a set because they are immutable,
making them useful for storing complex set elements.
•Representing Structured and Grouped Data
Tuples are ideal for grouping related data together in a single,
organized, and unchangeable structure.
Dictionaries: Key-value operations,
• A dictionary in Python is an unordered, mutable collection that
stores data in the form of key–value pairs.
Each key in a dictionary is unique and immutable (such as strings,
numbers, or tuples), while the values can be of any data type.
Dictionaries are mainly used for fast lookup, mapping, and organizing
data.
• Example (Conceptual):
{ key1: value1, key2: value2, key3: value3 }
• In short:
A dictionary is a data structure in Python that allows you to store
and retrieve data using unique keys instead of numeric indexes.
Characteristics of Dictionaries
a) Unordered
Dictionaries do not store data in a fixed order (before Python 3.7).
From Python 3.7+, insertion order is preserved, but ordering is not used for
indexing like lists.
b) Mutable
Dictionaries can be changed after creation.
You can add, update, or delete key–value pairs.
c) Indexed by Keys
Unlike lists which use numeric indexes, dictionaries use keys for accessing
values.
This makes lookups extremely fast.
d) Heterogeneous Data
Dictionaries can store different types of data in values.
How to Create a Dictionary
Dictionary can be created by placing a sequence of elements within
curly {} braces, separated by a 'comma’
d1 = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(d1)
# create dictionary using dict() constructor
d2 = dict(a = "Geeks", b = "for", c = "Geeks")
print(d2)
Output:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
{'a': 'Geeks', 'b': 'for', 'c': 'Geeks'}
.
Accessing Dictionary Items
We can access a value from a dictionary by using the key within square
brackets or get() method.
d = { "name": "Prajjwal", 1: "Python", (1, 2): [1,2,4] }
# Access using key
print(d["name"])
# Access using get()
print([Link]("name"))
Output:
Prajjwal
Prajjwal
Adding and Updating Dictionary Items
We can add new key-value pairs or update existing keys by using assignment.
d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
# Adding a new key-value pair
d["age"] = 22
# Updating an existing value
d[1] = "Python dict"
print(d)
Output:
{1: 'Python dict', 2: 'For', 3: 'Geeks', 'age': 22}
Iteration in dictionary
• There are several ways to iterate through a dictionary using a for loop,
depending on whether you need to access keys, values, or both.
• Iterating through Keys (Default Behavior)
• Iterating through Values
• Iterating through Key-Value Pairs
• Accessing Values using Keys during Iteration
Iterating through Keys (Default Behavior):
• When you iterate directly over a dictionary object in a for loop, it iterates over
its keys by default.
• Example:
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
for key in my_dict:
print(key)
Output:
name
age
city
Iterating through Values:
• Use the .values() method to iterate directly over the values of the dictionary.
• Example:
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
for value in my_dict.values():
print(value)
Output:
Alice
30
New York
Iterating through Key-Value Pairs:
• Use the .items() method to iterate over both keys and values
simultaneously. This method returns key-value pairs as tuples, which can be
unpacked directly in the for loop.
Example:
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
for key, value in my_dict.items():
print(f"Key: {key}, Value: {value}")
Output:
Key: name, Value: Alice
Key: age, Value: 30
Key: city, Value: New York
Accessing Values using Keys during Iteration:
• You can also iterate through the keys (as in the first method) and then access
the corresponding value within the loop using the key.
• Example:
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
for key in my_dict:
value = my_dict[key]
print(f"Key: {key}, Value: {value}")
Output:
Key: name, Value: Alice
Key: age, Value: 30
Key: city, Value: New York
Dictionary methods
Dictionary clear()
• The clear() method in Python is a built-in method that is used to remove
all the elements (key-value pairs) from a dictionary. It essentially
empties the dictionary, leaving it with no key-value pairs.
Example:
my_dict = {'1': 'Geeks', '2': 'For', '3': 'Geeks'}
my_dict.clear()
print(my_dict)
Output:
{}
Dictionary get()
• In Python, the get() method is a pre-built dictionary function that enables
you to obtain the value linked to a particular key in a dictionary. It is a
secure method to access dictionary values without causing a KeyError if
the key isn't present.
Example:
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
print([Link]('Name'))
print([Link]('Gender’))
Output:
Ram
None
Dictionary items()
• In Python, the items() method is a built-in dictionary function that retrieves a
view object containing a list of tuples. Each tuple represents a key-value pair
from the dictionary. This method is a convenient way to access both the keys
and values of a dictionary simultaneously, and it is highly efficient.
Example:
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
print(list([Link]())[1][0])
print(list([Link]())[1][1])
Output
Age
19
Dictionary update()
• Python's update() method is a built-in dictionary function that updates the
key-value pairs of a dictionary using elements from another dictionary or an
iterable of key-value pairs. With this method, you can include new data or
merge it with existing dictionary entries.
• Example:
d1 = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
d2 = {'Name': 'Neha', 'Age': '22'}
[Link](d2)
print(d1)
Output:
{'Name': 'Neha', 'Age': '22', 'Country': 'India'}
Dictionary pop()
• In Python, the pop() method is a pre-existing dictionary method that removes
and retrieves the value linked with a given key from a dictionary. If the key is
not present in the dictionary, you can set an optional default value to be
returned.
Example:
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
[Link]('Age')
print(d)
Output:
{'Name': 'Ram', 'Country': 'India'}
# Program to count the frequency of each word in a given sentence
# Accept a sentence from the user
sentence = input("Enter a sentence: ")
# Convert the entire sentence to lowercase Output:
sentence = [Link]() Enter a sentence: Python is fun and Python is
easy
# Split the sentence into individual words
words = [Link]() Word Frequency:
python: 2
# Create an empty dictionary to store word frequencies is: 2
frequency = {}
fun: 1
and: 1
# Loop through each word in the list
easy: 1
for word in words:
if word in frequency: # If the word is already in dict, increase count
frequency[word] = frequency[word] + 1
else: # Otherwise, add the word with count 1
frequency[word] = 1
# Display the frequency of each word
print("\nWord Frequency:")
for word, count in [Link]():
print(f"{word}: {count}")
Sets
• Sets in Python are an unordered collection of unique and immutable
elements. They are a built-in data type, similar to lists and tuples
• Properties
• Unordered: Elements in a set do not have a defined order, and their order
may change when the set is printed or iterated. This means you cannot access
elements by index.
• Unique elements: Sets automatically handle duplicate values, only storing
one instance of each element. If you attempt to add a duplicate, it will be
ignored.
•Mutable: While the elements within a set must be immutable (e.g.,
numbers, strings, tuples), the set itself is mutable. You can add or
remove elements from a set after its creation.
•Mathematical set operations:Sets support common mathematical set
operations like union, intersection, difference, and symmetric difference.
Set creation
• In Python, the most basic and efficient method for creating a set is
using curly braces.
• Example:
• set1 = {1, 2, 3, 4}
• print(set1)
• Output:
• {1, 2, 3, 4}
Using the set() Constructor
• Used when creating a set from lists, tuples, strings, etc.
my_set = set([10, 20, 30])
print(my_set)
Set operations
• Union
• Intersection
• Difference
Union:
• Combines all unique elements from two or more sets.
• Can be performed using the union() method or the | operator.
• Syntax
[Link](B)
# or
A|B
Or
A = {1, 2, 3}
B = {3, 4, 5}
print(A | B)
Intersection:
•Returns a new set containing only the elements common to all sets.
•Can be performed using the intersection() method or the & operator.
syntax
[Link](B)
# or
A&B
Difference:
•Returns a new set containing elements present in the first set but not in the second (or
subsequent) sets.
•Can be performed using the difference() method or the - operator.
Syntax:
[Link](B)
# or
A-B
Or
A = {1, 2, 3}
B = {3, 4, 5}
print(A & B)
Symmetric Difference ( A △ B )
• Elements that are in A or B but not in both.
Syntax
A.symmetric_difference(B)
# or
A^B
Example
A = {1, 2, 3}
B = {3, 4, 5}
print(A ^ B)
Output:
{1, 2, 4, 5}
Thank you