Python Prac3 14
Python Prac3 14
Practical 3
Aim: To implement Python programs using List, String, Set and Dictionary
1. To merge two list and find second largest element in the list using bubble sort
2. To calculate the no of uppercase, lowercase letters and digits in a string
3. To count the occurrences of each word in a given string sentence
4. To add key value pair to the dictionary and search and then delete the given key
from the dictionary
5. Create one dictionary of 5 students with their name, address, age, class and
marks of 5 subjects. Perform all the operations on the created dictionary
6. To concatenate two dictionaries and find sum of all values in dictionary
7. To add and remove elements from set and perform all the set operations like
Union, Intersection, Difference and Symmetric Difference
8. Perform different operations on Tuple.
9. Write a Python program to count the elements in a list until an element is a tuple.
Description:
In Python, `List`, `String`, `Set`, and `Dictionary` are all built-in data types that serve different
purposes and have unique characteristics. Here's a description of each with examples:
1. List:
• A list is an ordered collection of items, and it can contain elements of different data
types.
• Lists are mutable, meaning you can change their contents after they are created.
• Lists are defined using square brackets `[]` and can contain zero or more elements
separated by commas.
Example:
my_list = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed_list = [1, "hello", True, 3.14]
Page 2 of 24
Name : Prasad Gade FYMCA/A Roll No : 14
Slicing:
Example:
sliced_list = my_list[1:4] # Creates a new list (2, 3, 4)
Removing Elements:
Example:
my_list.remove(3) # Removes the first occurrence of 3
popped_element = my_list.pop() # Removes and returns the last element
2. String:
• A string is a sequence of characters, enclosed in either single (`'`) or double (`"`) quotes.
• Strings are immutable, which means once created, they cannot be changed.
• You can perform various string operations like concatenation, slicing, and formatting.
Example:
my_string = "Hello, World!"
name = "Alice"
greeting = f"Hello, {name}!"
String Length:
Example:
length = len(my_string) # Returns the length of the string
Page 3 of 24
Name : Prasad Gade FYMCA/A Roll No : 14
Substring:
Example:
substring = my_string[7:12] # Extracts "World"
String Methods:
Example:
uppercase_string = my_string.upper() # Converts to uppercase
3. Set:
Set Operations:
Example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2) # Union of sets (1, 2, 3, 4, 5)
intersection_set = set1.intersection(set2) # Intersection (3)
4. Dictionary:
Page 4 of 24
Name : Prasad Gade FYMCA/A Roll No : 14
• Dictionaries are defined using curly braces `{}` with key-value pairs separated by colons
`:`.
Example:
my_dict = {"name": "John", "age": 30, "city": "New York"}
student_scores = {"Alice": 95, "Bob": 87, "Charlie": 92}
These data types are fundamental in Python and are used extensively in various programming
tasks. Understanding when and how to use them is crucial for effective Python programming.
Page 5 of 24
Name : Prasad Gade FYMCA/A Roll No : 14
Page 6 of 24
Name : Prasad Gade FYMCA/A Roll No : 14
1. To merge two list and find second largest element in the list using bubble sort
Code:
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
list1 = [1,3,8,9]
list2 = [7,4,7,6]
second_largest = merged_list[-2]
print("Merged List:", merged_list)
print("Second Largest Element:", second_largest)
Conclusion:
The code successfully merges two lists (list1 and list2) into a single list (merged_list) and sorts it
using the Bubble Sort algorithm. After sorting, it finds and prints the second largest element in
the sorted merged_list. Please note that Bubble Sort is not the most efficient sorting algorithm,
especially for large lists, but it serves as an example for educational purposes.
Output:
Page 7 of 24
Name : Prasad Gade FYMCA/A Roll No : 14
Conclusion:
we have learned how to analyze a given input string in Python and count the occurrences of
uppercase letters, lowercase letters, and digits using string methods and loops.
Output:
Page 8 of 24
Name : Prasad Gade FYMCA/A Roll No : 14
Conclusion:
In this code, we've learned how to tokenize a sentence into words, create a dictionary to count
the frequency of each word, and print the word frequency count. This is a fundamental operation
often used in natural language processing and text analysis tasks
Output:
Page 9 of 24
Name : Prasad Gade FYMCA/A Roll No : 14
4. To add key value pair to the dictionary and search and then delete the given key from
the dictionary
Code:
my_dict = {}
my_dict['name'] = 'ABC'
my_dict['age'] = 31
my_dict['city'] = 'New York'
print("Dictionary after adding key-value pairs:")
print(my_dict)
search_key = 'age'
if search_key in my_dict:
print(f"The value for key '{search_key}' is: {my_dict[search_key]}")
else:
print(f"Key '{search_key}' not found in the dictionary")
delete_key = 'city'
if delete_key in my_dict:
del my_dict[delete_key]
print(f"Key '{delete_key}' deleted from the dictionary")
else:
print(f"Key '{delete_key}' not found in the dictionary")
Conclusion:
In this code, we've learned essential dictionary operations, including adding, searching for, and
deleting key-value pairs. This demonstrates how dictionaries are useful for organizing and
manipulating data in Python.
Page 10 of 24
Name : Prasad Gade FYMCA/A Roll No : 14
Output:
Page 11 of 24
Name : Prasad Gade FYMCA/A Roll No : 14
5. Create one dictionary of 5 students with their name, address, age, class and marks of 5
subjects. Perform all the operations on the created dictionary
Code:
# Create a dictionary for 5 students
students = {
'student1': {
'name': 'ABC',
'address': 'MU',
'age': 18,
'class': '11th',
'marks': {
'Mathematics': 85,
'science': 92,
'history': 78,
'english': 88,
'Drawing': 95
}
},
'student2': {
'name': 'DEF',
'address': 'NA',
'age': 17,
'class': '6th',
'marks': {
'Mathematics': 90,
'science': 88,
'history': 76,
'english': 91,
'Drawing': 84
}
Page 12 of 24
Name : Prasad Gade FYMCA/A Roll No : 14
},
'student3': {
'name': 'GHI',
'address': 'CH',
'age': 19,
'class': '10th',
'marks': {
'Mathematics': 78,
'science': 85,
'history': 92,
'english': 80,
'Drawing': 89
}
},
'student4': {
'name': 'JKL',
'address': 'MP',
'age': 17,
'class': '8th',
'marks': {
'Mathematics': 92,
'science': 84,
'history': 76,
'english': 90,
'Drawing': 82
}
},
'student5': {
'name': 'MNO',
'address': 'AG',
Page 13 of 24
Name : Prasad Gade FYMCA/A Roll No : 14
'age': 18,
'class': '9th',
'marks': {
'Mathematics': 88,
'science': 90,
'history': 85,
'english': 87,
'Drawing': 91
}
}
}
Page 14 of 24
Name : Prasad Gade FYMCA/A Roll No : 14
print(f"Name: {student_info['name']}")
else:
print(f"Student with ID '{search_id}' not found")
# Delete a student by ID
delete_id = 'student4'
if delete_id in students:
del students[delete_id]
print(f"Student with ID '{delete_id}' deleted from the dictionary")
else:
print(f"Student with ID '{delete_id}' not found in the dictionary")
Conclusion:
In this code, we've learned about dictionaries, nested dictionaries, and how to manipulate and
access data within them. It's a practical example of organizing and managing structured data in
Python, which is essential for various data processing and management tasks.
Page 15 of 24
Name : Prasad Gade FYMCA/A Roll No : 14
Output:
Page 16 of 24
Name : Prasad Gade FYMCA/A Roll No : 14
Page 17 of 24
Name : Prasad Gade FYMCA/A Roll No : 14
Conclusion:
In this code, we've learned how to merge two dictionaries into a single concatenated dictionary
and calculate the sum of values within it. This is a useful technique for combining data from
multiple sources and performing aggregate operations on the merged data
Output:
Page 18 of 24
Name : Prasad Gade FYMCA/A Roll No : 14
7. To add and remove elements from set and perform all the set operations like Union,
Intersection, Difference and Symmetric Difference
Code:
# Create two sets
set1 = {2, 3, 4, 5, 6}
set2 = {4, 5, 6, 7, 8}
Page 19 of 24
Name : Prasad Gade FYMCA/A Roll No : 14
Conclusion:
In this code, we've learned how to perform common set operations such as adding, removing,
finding the union, intersection, difference, and symmetric difference of sets. Sets are useful for
dealing with unique and unordered collections of elements in Python.
Output:
Page 20 of 24
Name : Prasad Gade FYMCA/A Roll No : 14
# Accessing elements
print("Accessing elements:")
print(my_tuple[0]) # Access the first element (1)
print(my_tuple[-1]) # Access the last element (5)
# Slicing
print("\nSlicing:")
sliced_tuple = my_tuple[1:4] # Creates a new tuple (2, 3, 4)
print(sliced_tuple)
# Concatenating tuples
print("\nConcatenating tuples:")
tuple1 = (1, 2)
tuple2 = (3, 4)
concatenated_tuple = tuple1 + tuple2 # Creates a new tuple (1, 2, 3, 4)
print(concatenated_tuple)
# Tuple repetition
print("\nTuple repetition:")
repeated_tuple = my_tuple * 2 # Creates a new tuple (1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
print(repeated_tuple)
Page 21 of 24
Name : Prasad Gade FYMCA/A Roll No : 14
print(length)
# Checking membership
print("\nChecking membership:")
if 12 in my_tuple:
print("3 is in the tuple")
# Tuple unpacking
print("\nTuple unpacking:")
a, b, c, d, e = my_tuple
print(f"a: {a}, b: {b}, c: {c}, d: {d}, e: {e}")
Conclusion:
In this code, we've learned various operations and techniques for working with tuples in Python.
Tuples are immutable, ordered collections of elements and can be useful in scenarios where
data should not be modified after creation
Page 22 of 24
Name : Prasad Gade FYMCA/A Roll No : 14
Output:
Page 23 of 24
Name : Prasad Gade FYMCA/A Roll No : 14
9. Write a Python program to count the elements in a list until an element is a tuple.
Code:
my_list = [11, 22, 33, 'world', (43, 54), 62, 71]
# Initialize a counter
count = 0
Conclusion:
In this code, we've learned how to iterate through a list and count the number of elements until a
specific condition is met (in this case, until a tuple is encountered). This demonstrates how to
use a for loop, conditionals, and the break statement for control flow in Python.
Output:
Page 24 of 24