0% found this document useful (0 votes)
44 views12 pages

Python String and List Manipulations

Python description

Uploaded by

aneesabano913
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views12 pages

Python String and List Manipulations

Python description

Uploaded by

aneesabano913
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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([Link]()) # Output: HELLO, WORLD!
print([Link]()) # Output: hello, world!
3. strip(): Removes any leading or trailing spaces from the string.
s2 = " Python Programming "
print([Link]()) # Output: Python Programming
4. replace(): Replaces a specified substring with another string.
print([Link]("World", "Universe")) # Output: Hello, Universe!
5. split(): Splits the string into a list, using a delimiter.
s3 = "apple,banana,cherry"
print([Link](",")) # 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([Link]("World")) # Output: 7
print([Link]("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']
[Link]('cherry')
print(fruits) # Output: ['apple', 'banana', 'cherry']
2. extend(): Adds all elements from another list to the end.
vegetables = ['carrot', 'tomato']
[Link](vegetables)
print(fruits) # Output: ['apple', 'banana', 'cherry', 'carrot', 'tomato']
3. insert(): Inserts an element at a specified position.
[Link](1, 'grape')
print(fruits) # Output: ['apple', 'grape', 'banana', 'cherry', 'carrot', 'tomato']
4. remove(): Removes the first occurrence of the specified element.
[Link]('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 = [Link]()
print(popped_item) # Output: 'tomato'
print(fruits) # Output: ['apple', 'grape', 'cherry', 'carrot']
6. sort(): Sorts the list in ascending order.
[Link]()
print(fruits) # Output: ['apple', 'carrot', 'cherry', 'grape']
7. reverse(): Reverses the order of the list.
[Link]()
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([Link](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([Link]('name')) # Output: Deepal
print([Link]('address', 'Not Found')) # Output: Not Found
2. keys() / values(): Returns a list of the dictionary’s keys or values.
print([Link]()) # Output: dict_keys(['name', 'age'])
print([Link]()) # Output: dict_values(['Deepal', 21])
3. items(): Returns a list of key-value pairs.
print([Link]()) # Output: dict_items([('name', 'Deepal'), ('age', 21)])
4. update(): Updates the dictionary with key-value pairs from another
dictionary.
[Link]({'address': 'India'})
print(person) # Output: {'name': 'Deepal', 'age': 21, 'address': 'India'}
5. pop(): Removes a key-value pair and returns the value.
age = [Link]('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.
[Link]()
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 = [Link]().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
[Link](6)
[Link]()
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
[Link]({'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 = [Link]().strip()
sentence = [Link]('python', 'PYTHON')
words = [Link]()
print("Words in sentence:", [[Link]() for word in words])
print("Word count:", len(words))
final_sentence = " ".join([[Link]() 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]
[Link](30)
[Link](2, 12)
[Link](reverse=True)
popped = [Link]()
count_15 = [Link](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'}
[Link]({'location': 'India', 'age': 26})
print("Dictionary after updates:", person)

profession = [Link]('profession')
print("Profession:", profession)

print("All keys:", list([Link]()))


print("All values:", list([Link]()))

[Link]()
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 = [Link]()
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 = [[Link]() 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).

Common questions

Powered by AI

String, list, and dictionary methods can be integrated into comprehensive solutions for robust text and data processing in Python. Strings can be split into lists of words with 'split()', cleaned, and analyzed for frequency using dictionary methods such as 'get()' and 'update()'. Lists allow for sorted and ordered manipulation of data, benefiting from their mutable nature. This interoperability enables complex data transformations, facilitating tasks like parsing and aggregating textual datasets for natural language processing or data analysis projects .

In-built methods in Python are crucial for manipulating both immutable and mutable data types, providing a variety of functionalities without altering the original immutable structures like strings. For example, methods such as 'upper()', 'replace()', and 'split()' work on strings (immutable) by creating and returning new strings based on manipulations. On the other hand, for mutable data types like lists and dictionaries, methods such as 'append()', 'extend()', 'update()', and 'pop()' directly modify the original data structures, enabling dynamic data handling .

The 'pop()' method serves diverse roles depending on whether it's used in a list or dictionary in Python. With lists, 'pop()' removes and returns an element at the given index or the last element, facilitating stack-like operations or specific data extraction. In dictionaries, 'pop()' requires a key and removes the associated key-value pair, returning the value. These differing behaviors enhance data management by permitting element manipulation with precision in lists and efficient key-value pair removal in dictionaries .

Python's string methods such as 'strip()', 'replace()', 'split()', and 'join()' can be combined to clean and format text, enhancing readability and facilitating analysis. For instance, 'strip()' removes unwanted spaces, 'replace()' can standardize terms, while 'split()' and 'join()' can reformat the text structure for consistent presentation or further processing. This enables preparation of text for tasks such as sentiment analysis or structured data input .

The fundamental difference between mutable and immutable data types in Python lies in their ability to be modified after creation. Immutable data types, such as strings and tuples, do not allow in-place changes, meaning all manipulations result in new objects. This immutability ensures data integrity and predictability across functions and program executions. Conversely, mutable types, like lists and dictionaries, can be altered in-place, enabling dynamic data manipulations and efficient memory utilization, but they require careful handling to avoid unintended side-effects .

Dictionary methods in Python are pivotal for effectively organizing and modifying key-value pair data. Methods such as 'get()', 'keys()', and 'values()' facilitate efficient data retrieval, while 'update()' and 'pop()' allow for seamless updates and deletions of key-value pairs, thereby enhancing data management and supporting complex data transactions .

List methods in Python, such as 'append()', 'insert()', 'remove()', and 'sort()', afford users the ability to dynamically build and alter sequences of data. 'append()' and 'extend()' allow for sequence expansion, while 'insert()' gives precise control over element placement. Methods like 'remove()', 'pop()', and 'sort()' are fundamental for refining lists by eliminating unwanted elements and ensuring ordered data. Together, these methods support comprehensive data management within Python applications .

The immutability of strings in Python can lead to challenges in performance and memory usage when frequent manipulations are necessary since each change creates a new string object. This can be overcome by using alternative mutable data structures like lists to gather or build data before converting it back to a string with 'join()', or leveraging libraries like 'io.StringIO' for buffer-efficient string manipulation, optimizing both operational complexity and resource consumption .

Control flow structures in Python, such as conditional statements ('if', 'else', 'elif') and loops ('for', 'while'), are essential for guiding the execution path of a program. They enable programmers to dictate conditions under which certain code segments are executed, iterate over data structures, and manage decision-making processes, thereby allowing for flexible and efficient algorithm development .

Dictionaries provide a more efficient mechanism than lists for counting word frequencies in text due to their hash table-based implementation, offering average O(1) time complexity for inserts and lookups. This makes counting occurrences and retrieving word frequencies in larger datasets significantly faster compared to the O(n) operations required by lists for each search and update, especially beneficial when processing large text corpora for tasks such as frequency analysis and data aggregation .

You might also like