Unit 04 Notes

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

Unit 04: Python String, List, and Dictionary Manipulations

Introduction to the Unit


This unit focuses on fundamental Python data types—Strings, Lists, and
Dictionaries—and various in-built methods used for manipulating these data
structures. These data types are crucial for handling and organizing data in
Python programs. Mastery over string, list, and dictionary manipulation allows
for efficient data handling, problem-solving, and the development of complex
algorithms.
Building Blocks of Python Programs
The basic building blocks of Python programs are data types and their
associated methods, which help perform operations on these data types.
1. Data Types in Python:
o Strings: Immutable sequences of characters.
o Lists: Ordered, mutable collections of items.
o Dictionaries: ordered collections of key-value pairs.
2. Control Flow:
o Python includes control structures such as conditional statements
(if, else, elif) and loops (for, while) that guide the flow of the
program.
3. Functions:
o Python functions, both in-built and user-defined, allow code
reusability. They can manipulate data types by performing specific
operations such as concatenation, searching, updating, or
iterating.

Understanding String In-Built Methods


Strings are immutable sequences of characters in Python. Various methods
allow manipulation, but they return a new string, leaving the original
unchanged. Some common in-built string methods include:
1. len(): Returns the length of a string.
s = "Hello, World!"
print(len(s)) # Output: 13
2. upper() / lower(): Converts the string to uppercase or lowercase.
print(s.upper()) # Output: HELLO, WORLD!
print(s.lower()) # Output: hello, world!
3. strip(): Removes any leading or trailing spaces from the string.
s2 = " Python Programming "
print(s2.strip()) # Output: Python Programming
4. replace(): Replaces a specified substring with another string.
print(s.replace("World", "Universe")) # Output: Hello, Universe!
5. split(): Splits the string into a list, using a delimiter.
s3 = "apple,banana,cherry"
print(s3.split(",")) # Output: ['apple', 'banana', 'cherry']
6. join(): Joins a list of strings into a single string.
words = ["MCA", "Students", "Rocks"]
print(" ".join(words)) # Output: MCA Students Rocks
7. find() / index(): Searches for a substring and returns its position. find()
returns -1 if the substring is not found, while index() raises an error.
print(s.find("World")) # Output: 7
print(s.index("World")) # Output: 7

String Exercise :
o Sample Input: " I am learning python programming and Python is
great! "
o Expected Output:
▪ Words in sentence: ['I', 'Am', 'Learning', 'PYTHON',
'Programming', 'And', 'PYTHON', 'Is', 'Great!']
▪ Word count: 9
▪ Final formatted sentence: "I Am Learning PYTHON
Programming And PYTHON Is Great!"

List Manipulation Using In-Built Methods


Lists are mutable, meaning they can be modified after their creation. Python
provides several in-built methods to perform operations on lists.
1. append(): Adds an element to the end of the list.
fruits = ['apple', 'banana']
fruits.append('cherry')
print(fruits) # Output: ['apple', 'banana', 'cherry']
2. extend(): Adds all elements from another list to the end.
vegetables = ['carrot', 'tomato']
fruits.extend(vegetables)
print(fruits) # Output: ['apple', 'banana', 'cherry', 'carrot', 'tomato']
3. insert(): Inserts an element at a specified position.
fruits.insert(1, 'grape')
print(fruits) # Output: ['apple', 'grape', 'banana', 'cherry', 'carrot', 'tomato']
4. remove(): Removes the first occurrence of the specified element.
fruits.remove('banana')
print(fruits) # Output: ['apple', 'grape', 'cherry', 'carrot', 'tomato']
5. pop(): Removes and returns the last element (or element at a specified
index).
popped_item = fruits.pop()
print(popped_item) # Output: 'tomato'
print(fruits) # Output: ['apple', 'grape', 'cherry', 'carrot']
6. sort(): Sorts the list in ascending order.
fruits.sort()
print(fruits) # Output: ['apple', 'carrot', 'cherry', 'grape']
7. reverse(): Reverses the order of the list.
fruits.reverse()
print(fruits) # Output: ['grape', 'cherry', 'carrot', 'apple']
8. count(): Counts how many times an element appears in the list.
numbers = [1, 2, 2, 3, 2, 4, 5]
print(numbers.count(2)) # Output: 3

Dictionary Manipulation
Dictionaries are collections of key-value pairs, and Python offers several
methods to manipulate them.
1. get(): Returns the value for a specified key. If the key doesn't exist, it
returns None (or an optional default value).
person = {'name': 'Deepal', 'age': 22}
print(person.get('name')) # Output: Deepal
print(person.get('address', 'Not Found')) # Output: Not Found
2. keys() / values(): Returns a list of the dictionary’s keys or values.
print(person.keys()) # Output: dict_keys(['name', 'age'])
print(person.values()) # Output: dict_values(['Deepal', 21])
3. items(): Returns a list of key-value pairs.
print(person.items()) # Output: dict_items([('name', 'Deepal'), ('age', 21)])
4. update(): Updates the dictionary with key-value pairs from another
dictionary.
person.update({'address': 'India'})
print(person) # Output: {'name': 'Deepal', 'age': 21, 'address': 'India'}
5. pop(): Removes a key-value pair and returns the value.
age = person.pop('age')
print(age) # Output: 21
print(person) # Output: {'name': 'Deepal', 'address': 'India'}
Difference between pop() & popitem()
6. clear(): Removes all key-value pairs from the dictionary.
person.clear()
print(person) # Output: {}

Programming Using String, List, and Dictionary In-Built Functions


Here are some examples of Python programs that manipulate strings, lists, and
dictionaries.
1. String Manipulation Example:
sentence = " Python is amazing! "
# Using various string methods
cleaned_sentence = sentence.strip().upper().replace("AMAZING", "AWESOME")
print(cleaned_sentence) # Output: PYTHON IS AWESOME!
2. List Manipulation Example:
numbers = [1, 2, 3, 4, 5]
# Adding an element, reversing, and finding sum
numbers.append(6)
numbers.reverse()
total = sum(numbers)
print(numbers) # Output: [6, 5, 4, 3, 2, 1]
print(total) # Output: 21
3. Dictionary Manipulation Example:
student = {'name': 'Alice', 'marks': 85}
# Updating marks and adding a new key
student['marks'] = 90
student.update({'subject': 'Math'})
print(student) # Output: {'name': 'Alice', 'marks': 90, 'subject': 'Math'}

Lab Exercise to understand the concepts in better way


Step 1: String Manipulation
Task 1: String Formatting and Manipulation
2. Problem Statement:
Write a Python program that:
o Takes an input sentence from the user.
o Converts the sentence into lowercase and removes leading and
trailing spaces.
o Replaces all occurrences of the word "python" with "PYTHON"
(case insensitive).
o Splits the sentence into words and counts the number of words.
o Joins the words back into a sentence with each word capitalized.
3. Instructions:
o Use
o Sample Input: " I am learning python programming and Python is
great! "
o Expected Output:
▪ Words in sentence: ['I', 'Am', 'Learning', 'PYTHON',
'Programming', 'And', 'PYTHON', 'Is', 'Great!']
▪ Word count: 9
▪ Final formatted sentence: "I Am Learning PYTHON
Programming And PYTHON Is Great!"
4. Code Skeleton:
sentence = input("Enter a sentence: ")
sentence = sentence.lower().strip()
sentence = sentence.replace('python', 'PYTHON')
words = sentence.split()
print("Words in sentence:", [word.capitalize() for word in words])
print("Word count:", len(words))
final_sentence = " ".join([word.capitalize() for word in words])
print("Final formatted sentence:", final_sentence)

Step 2: List Manipulation


Task 2: List Operations
1. Problem Statement:
Write a Python program that:
o Initializes a list with the following elements: [5, 10, 15, 20, 25].
o Appends the value 30 to the list.
o Inserts the value 12 at the third position.
o Sorts the list in descending order.
o Removes the last element and displays it.
o Counts how many times 15 appears in the list.
2. Instructions:
o Use append(), insert(), sort(), pop(), and count() methods.
o Expected Output:
▪ Final List: [30, 25, 20, 15, 12, 10, 5]
▪ Popped Element: 5
▪ Count of 15: 1
3. Code Skeleton:
numbers = [5, 10, 15, 20, 25]
numbers.append(30)
numbers.insert(2, 12)
numbers.sort(reverse=True)
popped = numbers.pop()
count_15 = numbers.count(15)

print("Final List:", numbers)


print("Popped Element:", popped)
print("Count of 15:", count_15)

Step 3: Dictionary Manipulation


Task 3: Dictionary Operations
1. Problem Statement:
Write a Python program that:
o Initializes a dictionary with the following key-value pairs: {'name':
'Varun', 'age': 21, 'profession': 'Student'}.
o Adds a new key-value pair: 'location': 'India'.
o Updates the value of 'age' to 26.
o Displays all the keys and values in the dictionary.
o Removes the 'profession' key and prints its value.
o Clears the dictionary at the end and shows the final state.
2. Instructions:
o Use update(), pop(), keys(), values(), and clear() methods.
o Expected Output:
▪ Dictionary after updates: {'name': 'Varun, 'age': 26,
'location': 'India'}
▪ Profession: Student
▪ Final Dictionary: {}
3. Code Skeleton:
person = {'name': 'Varun', 'age': 21, 'profession': 'Student'}
person.update({'location': 'India', 'age': 26})
print("Dictionary after updates:", person)

profession = person.pop('profession')
print("Profession:", profession)

print("All keys:", list(person.keys()))


print("All values:", list(person.values()))

person.clear()
print("Final Dictionary:", person)

Step 4: Combining String, List, and Dictionary Manipulation


Task 4: Text Analysis
1. Problem Statement:
Write a Python program that:
o Takes a paragraph of text as input.
o Splits the paragraph into individual words.
o Stores the words and their respective frequencies in a dictionary.
o Sorts the dictionary by frequency in descending order.
o Converts the top 5 words to uppercase and adds them to a list.
o Prints the dictionary and the final list of top 5 words.
2. Instructions:
o Use string methods like split(), list methods like append() and
sort(), and dictionary methods like items().
o Sample Input: "Python is great. Python is easy. Learning Python is
fun!"
o Expected Output:
▪ Word frequencies: {'python': 3, 'is': 3, 'great': 1, 'easy': 1,
'learning': 1, 'fun': 1}
▪ Top 5 words in uppercase: ['PYTHON', 'IS', 'GREAT', 'EASY',
'LEARNING']
3. Code Skeleton:
paragraph = input("Enter a paragraph: ").lower()
words = paragraph.split()
word_freq = {}

for word in words:


word_freq[word] = word_freq.get(word, 0) + 1

sorted_words = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)

top_5_words = [word.upper() for word, freq in sorted_words[:5]]

print("Word Frequencies:", word_freq)


print("Top 5 words in uppercase:", top_5_words)
Task 5: Create a Student Database
1. Problem Statement:
Write a Python program that:
o Initializes an empty dictionary to store student information.
o Takes student details (name, age, grades) from the user.
o Stores each student’s details in the dictionary with the name as
the key and a nested dictionary for age and grades.
o Allows the user to update student grades and view all student
data.
o Calculates the average grade for each student and prints it.
2. Instructions:
o Use nested dictionaries for student records.
o Allow for dynamic entry and update of student data.
o Sample Input/Output:
▪ Enter name: John
▪ Enter age: 20
▪ Enter grades (comma separated): 85, 90, 95
▪ Update grades for John? (y/n): y
▪ Enter new grades (comma separated): 88, 92, 96
▪ Average grade for John: 92.0

Conditional Dictionary
Given a dictionary of items and their prices, {"apple": 10, "banana": 5,
"cherry": 15}, write a program to print only the items whose price is
greater than or equal to 10.

Dictionary Assignment :
1. Create a dictionary with the following key-value pairs:
{'product': 'Laptop', 'brand': 'Dell', 'price': 60000}.
2. Add a new key-value pair to the dictionary: 'warranty': '2 years'.
3. Update the value of the 'price' key to 55000.
4. Print all the keys and values in the dictionary in a user-friendly format.
5. Remove the 'brand' key from the dictionary and print the removed
value.
6. Check if the key 'product' exists in the dictionary. If it exists, print its
value. If not, print "Product not found"
7. Clear all items from the dictionary and show the final state (it should
be empty).

You might also like