0% found this document useful (0 votes)
6 views11 pages

Python Collections: Strings, Lists, and More

Unit 5 of the document focuses on Python collections, detailing core types such as Strings, Lists, Tuples, Sets, and Dictionaries. It emphasizes the importance of collections in managing groups of data efficiently, highlighting their properties, operations, and use cases. The chapter also covers specific characteristics of strings and lists, including mutability, indexing, slicing, and common methods.

Uploaded by

pawanmahato004
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)
6 views11 pages

Python Collections: Strings, Lists, and More

Unit 5 of the document focuses on Python collections, detailing core types such as Strings, Lists, Tuples, Sets, and Dictionaries. It emphasizes the importance of collections in managing groups of data efficiently, highlighting their properties, operations, and use cases. The chapter also covers specific characteristics of strings and lists, including mutability, indexing, slicing, and common methods.

Uploaded by

pawanmahato004
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 5: Python Collections​

​Chapter Introduction​
​ elcome to Unit 5. In the world of programming, data is the raw material from which we build solutions. While simple variables can hold​
W
​a single piece of data, the real power of programming is unlocked when we can work with groups of data. Collections are the​
​fundamental building blocks in Python for storing, organizing, and managing these groups. This chapter will provide a comprehensive,​
​exam-oriented exploration of Python's core collection types: Strings, Lists, Tuples, Sets, and Dictionaries. We will deconstruct their​
​properties, examine their unique strengths, and learn how to manipulate them effectively. Mastering these data structures is not just an​
​academic exercise; it is an essential skill for solving any significant programming problem, forming the bedrock upon which more​
​complex programs are built.​

​--------------------------------------------------------------------------------​

​1.0 Introduction to Collections in Python​


​ s we move beyond programs that handle only a few pieces of information, we encounter a strategic challenge: how do we manage​
A
​dozens, hundreds, or even millions of related values efficiently? Using a separate variable for each value is impractical and unscalable.​
​This is where collections come into play. Collections, or data structures, are the tools that allow a programmer to bundle multiple values​
​into a single, manageable entity, forming the basis for any sophisticated application.​

​ ​​collection​​(also known as a container) is a programming​​construct—a data type specifically designed to group and store other​
A
​objects. Think of a collection as a box that can hold multiple items, allowing you to carry them all around using a single name.​

​ he need for collections is intuitive and mirrors how we organize information in daily life. Imagine trying to create a shopping list where​
T
​each item required a separate piece of paper. It would be incredibly inefficient. Instead, we use a single list—a collection—to hold all the​
​items. Similarly, a phonebook is a collection that maps names to numbers. Without such structures, programs would be limited to trivial​
​tasks. The ability to store multiple student grades in one list, or all employee details in a single data structure, is what makes​
​programming a powerful tool for solving real-world problems.​

​ ifferent collections have different properties, and choosing the right one for the job is a critical programming skill. Some collections​
D
​maintain a specific order, some are designed to be changed after creation, while others enforce uniqueness among their items.​
​Understanding these characteristics is key to writing efficient and correct code. We will begin our exploration with the most fundamental​
​collection of all, one we have already encountered but will now examine in depth: the string.​

​2.0 The String (​​


str​
​): An Immutable Sequence of Characters​
​ hile strings may appear to be simple text, they are, in fact, powerful and fundamental collection types in Python. Every time you work​
W
​with a username, a line from a file, or a message to display, you are using a string. This section will deconstruct the properties and​
​operations of strings, which are crucial for handling any text-based data in your programs.​

​2.1 Definition and Core Characteristics​


​ or exam purposes, a Python​​string​​should be defined​​as a​​sequence of characters​​. This definition highlights​​its two core​
F
​characteristics:​

​1.​ O ​ rdered​​: The characters in a string have a defined,​​predictable position. The first character is always at the beginning, the​
​second follows it, and so on. This reliable ordering allows us to access characters by their position.​
​2.​ ​Immutable​​: Once a string is created, it cannot be​​changed in-place. Any operation that appears to modify a string, such as​
​replacing a character, actually creates and returns an entirely​​new​​string. This is a critical concept.​

TypeError​
​Attempting to change a character in a string will result in a​​ ​, a common point of examination.​

​ Create a string​
#
​my_string = "Python"​

​ Try to change the first character from 'P' to 'J'​


#
​my_string[0] = 'J' # This will cause an error!​
​ Output:​
#
​# TypeError: 'str' object does not support item assignment​

​2.2 Indexing and Slicing​


​ ecause strings are ordered, we can access their individual elements using a numeric index. Python uses​​zero-based​​indexing​​,​
B
0​.​​
​meaning the first character is at index​​

'Python'​​as follows:​
​We can visualize the indices for the string​​

​●​ ​Positive Indices (from the start):​


​○​ ​Character:​​ P y t h o n​
​○​ ​Index:​​ 0 1 2 3 4 5​
​●​ ​Negative Indices (from the end):​
P y t h o n​
​○​ ​Character:​​
-6 -5 -4 -3 -2 -1​
​○​ ​Index:​​

[start:stop:step]​
​ licing​​is the technique for extracting a portion​​of a string (a substring). It uses the syntax​​
S stop​​is the​
​,​​where​​
​first index​​not​​included in the slice.​

​​
● ​[1:4]​​extracts characters from index 1 up to (but​​not including) index 4 (​​
s 'yth'​
​).​
​●​ s[:3]​​extracts characters from the beginning up to​​index 3 (​​
​ 'Pyt'​ ​).​
​●​ s[2:]​​extracts characters from index 2 all the way​​to the end (​​
​ 'thon'​ ​).​
​●​ s[-2:]​​extracts the last two characters (​​
​ 'on'​ ​).​

​2.3 Common String Operations​


​Basic operations allow us to combine and replicate strings in intuitive ways.​

​Operation​ ​Description & Example​

​Concatenation (​​
+​​)​ 'Hello' + ' ' + 'World'​​results in​
J​ oins two strings together to create a new string.​​
'Hello World'​
​ ​.​

​Repetition (​​
*​ ​)​ 'Go' *​
​ reates a new string by repeating an existing string a specified number of times.​​
C
3​​results in​​
​ 'GoGoGo'​​.​

​Membership (​​
in​
​)​ True​​or​​
​ hecks if a substring exists within a larger string, returning​​
C False​ 'on' in​
​.​​
'Python'​​results in​​
​ True​ ​.​

​2.4 Essential String Methods​


​ s objects, strings come with built-in functions called​​methods​​that perform common tasks. A method is called​​using dot notation (e.g.,​
A
my_string.lower()​
​ ​).​

​Method​ ​Purpose​ ​Example​


.lower()​
​ ​ eturns a new string with all characters​
R 'Python'.lower()​​results in​​
​ 'python'​
​.​
​converted to lowercase.​

.upper()​
​ ​ eturns a new string with all characters​
R 'Python'.upper()​​results in​​
​ 'PYTHON'​
​.​
​converted to uppercase.​

.find(sub)​
​ ​ eturns the index of the first occurrence of​ ​
R 'Python'.find('ho')​​results in​​
3​.​​
sub​
​ -1​​if not found.​
​. Returns​​

​replace(old,​
. ​ eturns a new string where all​
R ​Hello'.replace('l', 'w')​​results in​
'
new)​
​ old​​are replaced with​​
​occurrences of​​ new​
​.​ ​
'Hewwo'​
​.​

.split(sep)​
​ ​ eturns a list of substrings, splitting the​
R ​cat,dog,fish'.split(',')​​results in​
'
sep​
​original string at the separator​​ ​.​ ['cat', 'dog', 'fish']​
​ ​.​

.join(iterable)​
​ J​ oins elements of an iterable (like a list)​ ​-'.join(['a', 'b', 'c'])​​results in​
'
​into a single string, using the string as a​ 'a-b-c'​
​ ​.​
​separator.​

.isalpha()​
​ True​​if all characters in the string​
​ eturns​​
R 'abc'.isalpha()​​results in​​
​ True​
​.​
False​​otherwise.​
​are alphabetic,​​

​2.5 String Formatting​


​ mbedding variable values within a string is a common requirement. While the older​​
E .format()​​method exists,​​modern Python​
​strongly favors​​f-strings​​(formatted string literals)​​for their superior readability and performance. An f-string is a literal string prefixed​
f​​or​​
​with​​ F​ {}​​evaluated at runtime and inserted into the string.​
​, with expressions inside curly braces​​

​ ame = "Adam"​
n
​age = 20​
​# Using an f-string to embed variables​
​message = f"{name} is {age} years old."​
​print(message)​

​ Output:​
#
​# Adam is 20 years old.​

​ trings are powerful but rigid due to their immutability. For a collection that needs to be modified after creation, we turn to Python's most​
S
​versatile sequence type: the list.​

​3.0 The List (​​


list​
​): A Mutable and Ordered Sequence​
​ hat makes the Python list the most versatile and frequently used collection in a programmer's toolkit? It is its unparalleled flexibility as​
W
​the primary tool for managing ordered collections of items that may need to be altered during a program's execution. This makes it the​
​go-to data structure for a vast range of problems, from storing user inputs to managing items in a game.​
​3.1 Definition and Core Characteristics​
​A Python​​list​​is a container that holds a collection​​of objects in a specific order. Its core characteristics are:​

​1.​ M ​ utable​​: This is the key difference from strings.​​Lists can be changed in-place. You can add, remove, or change elements​
​after the list has been created.​
​2.​ ​Ordered​​: A list maintains the order of insertion.​​The first item added stays at the beginning, and subsequent items are added​
​to the end, unless specified otherwise.​
​3.​ ​Allows Duplicates​​: A list can contain multiple instances​​of the same element.​

​3.2 List Creation, Indexing, and Slicing​


[]​
​A list is created by placing comma-separated values inside square brackets​​ ​.​

​ A list of integers​
#
​scores = [95, 88, 73, 95, 100]​

​ A list with mixed data types​


#
​student_info = ['Alice', 21, 'Computer Science']​

J​ ust like strings, lists support​​zero-based indexing​​to access elements and​​slicing​​to extract sub-lists.​​The syntax and behavior are​
​identical.​

​ rades = ['A', 'B', 'C', 'D', 'F']​


g
​print(grades[0]) # Accesses the first element: 'A'​
​print(grades[-1]) # Accesses the last element: 'F'​
​print(grades[1:4]) # Slices from index 1 to 3: ['B', 'C', 'D']​

​3.3 Modifying Lists: Adding and Removing Elements​


​The mutability of lists is expressed through methods that modify the list directly.​

​Method​ ​Description​ ​Code Example​ ​Resulting List​

.append(item)​
​ item​​to the end of the list.​
​Adds a single​​ ​tems = [1,​
i [1, 2, 3]​

2]​
​ ​<br>​​
[Link](3)​

.extend(list)​
​ list​​to​
​ ppends all items from another​​
A ​tems = [1,​
i ​1, 2, 3,​
[
​the end.​ 2]​
​ ​<br>​​
[Link]([3, 4])​ ​
4]​

​insert(i,​
. item​​at a specific index​​
​Inserts an​​ i​.​​ ​tems = [1,​
i [1, 2, 3]​

item)​
​ 3]​
​ ​<br>​​
[Link](1, 2)​

.remove(item)​
​ item​
​ emoves the​​first​​occurrence of​​
R ​tems = [1, 2, 3,​
i [1, 3, 2]​

​from the list. Raises a​​ValueError​​if​ 2]​
​ ​<br>​​
[Link](2)​
​the item is not found.​
.pop(i)​
​ ​ emoves and returns the item at index​​
R i​.​​ i
​tems = [1, 2,​ ​1, 3]​​(and​
[
i​​is omitted, it removes and returns the​ ​
​If​​ 3]​
​<br>​​
[Link](1)​ 2​)​​
​returns​​
​last item.​

​3.4 Introduction to List Comprehensions​


​ ist comprehensions offer a concise and elegant syntax for creating lists. This "Pythonic" approach is often more readable and efficient​
L
for​​loop. The basic structure​​is​​
​than using an explicit​​ [expression for item in iterable]​ ​.​

​Consider creating a list of the squares of the first ten integers.​

for​​loop:​
​Using a​​

s​ quares = []​
​for x in range(10):​
​[Link](x**2)​

​Using a list comprehension:​

​squares = [x**2 for x in range(10)]​

​ oth produce the same result—​​


B [0, 1, 4, 9, 16, 25,​​
36, 49, 64, 81]​
​—but the comprehension is more direct​​and​
​expressive.​

​3.5 Nested Lists​


​ list can contain any type of object, including another list. This is known as a​​nested list​​. Nested lists​​are a natural way to represent​
A
​2D structures like matrices, grids, or game boards.​

​Elements in a nested list are accessed using multiple indices.​

​ A 2x2 matrix represented as a nested list​


#
​matrix = [​
​[1, 2],​
​[3, 4]​
​]​

​ Access the element in the first row (index 0), second column (index 1)​
#
​element = matrix[0][1]​
​print(element) # Output: 2​

​ hile lists are incredibly flexible due to their mutability, some situations require a guarantee that data will not change. For this, Python​
W
​provides another sequence type: the tuple.​

​4.0 The Tuple (​​


tuple​
​): An Immutable Ordered Sequence​
​ ositioned as the immutable counterpart to lists, tuples play a crucial strategic role in Python programming. They are used to store​
P
​collections of items that are fixed and should not be changed. This immutability provides a safeguard against accidental modification,​
​making the code safer and more predictable, especially in larger applications.​

​4.1 Definition and Properties​


​ ​​tuple​​is a collection of objects that is​​ordered​​and, most importantly,​​immutable​​. Once a tuple is​​created, its contents cannot be​
A
​altered, added to, or removed. This makes it a reliable container for data that must remain constant throughout its lifecycle.​
​4.2 Tuple Creation and Access​
()​
​Tuples are created by enclosing comma-separated values in parentheses​​ ​.​

​ A tuple of coordinates​
#
​point = (10, 20)​

​ A tuple with mixed data types​


#
​record = ('John Doe', 34, 'Manager')​

​ peculiar but important syntax rule applies when creating a tuple with a single element: it must have a trailing comma. This​
A
​distinguishes it from a value simply enclosed in parentheses for mathematical grouping.​

s​ ingle_item_tuple = (1,) # This is a tuple​


​not_a_tuple = (1) # This is just the integer 1​

​Accessing elements via​​indexing and slicing​​works​​exactly as it does for strings and lists.​

​4.3 Tuple Packing and Unpacking​


​Python provides a highly convenient syntax for working with tuples.​

​​
● ​ uple Packing​​: When you assign several comma-separated​​values to a single variable, Python "packs" them into a tuple.​
T
​●​ ​Tuple Unpacking​​: You can assign the elements of a​​tuple to multiple variables in a single statement. This is known as​
​"unpacking" and is extremely useful for assignments.​

​4.4 Use-Cases: Tuples vs. Lists​


​ common and important exam question is, "When should I use a tuple instead of a list?" The choice is driven by intent and technical​
A
​constraints.​

​●​ ​ ata Integrity​​: Use a tuple for collections of data​​that should not be modified after creation. Examples include configuration​
D
​settings, fixed coordinates, or records from a database.​
​●​ ​Performance​​: Tuples can be slightly more memory-efficient​​and faster to process than lists in certain contexts, as their fixed​
​size allows for internal optimizations.​
​●​ ​Dictionary Keys​​: Dictionaries require their keys to​​be immutable. Since lists are mutable, they cannot be used as dictionary​
​keys, but tuples can.​

​ rom ordered collections, we now shift our focus to collections where order is not a primary concern, but uniqueness is paramount,​
F
​which brings us to the set.​

​5.0 The Set (​​


set​
​): A Mutable Collection of Unique​​Elements​
​ ow can we efficiently manage collections where uniqueness is the only requirement, and order is irrelevant? Drawing inspiration from​
H
​mathematical theory, Python's​​ set​​provides an elegant​​and powerful answer. Its strategic importance lies in its ability to automatically​
​enforce uniqueness and to perform standard mathematical set operations like union, intersection, and difference, which are invaluable​
​for data analysis and comparison tasks.​

​5.1 Definition and Characteristics​


​A​​set​​is a collection of items with no defined order​​and no duplicate elements. Its core characteristics are:​

​ .​ U
1 ​ nordered​​: The items in a set do not have a fixed​​position or index. The order in which items are stored is not guaranteed.​
​2.​ ​Mutable​​: Sets can be modified after creation; you​​can add or remove elements.​
​3.​ ​Unique Elements​​: Sets automatically enforce uniqueness.​​If you attempt to add an item that is already present, the set​
​remains unchanged.​

​5.2 Creating and Modifying Sets​


set()​​constructor. This is a common technique to remove​
​ set is typically created from an existing iterable (like a list) using the​​
A
​duplicates from a list.​

​ umbers = [1, 2, 2, 3, 4, 3, 5]​


n
​unique_numbers = set(numbers)​
​print(unique_numbers) # Output: {1, 2, 3, 4, 5}​

.add()​​method​​and removed with the​​


​Elements are added to a set using the​​ .remove()​​method.​

​ y_set = {1, 2, 3}​


m
​my_set.add(4) # my_set is now {1, 2, 3, 4}​
​my_set.remove(2) # my_set is now {1, 3, 4}​

​5.3 Set Operations for Data Analysis​


​ ets are exceptionally powerful for comparing the contents of two collections. They provide fast, optimized methods and operators for​
S
​classical set theory operations.​

​Operation​ ​Description & Example Code​

​Union (​​
|​​)​ set_a = {1, 2,​
​ ombines all unique elements from both sets.​​<br>​​
C
3}​
​ ​<br>​​
set_b = {3, 4, 5}​​<br>​​
set_a | set_b​​results in​​
{1, 2, 3, 4, 5}​
​.​

​Intersection (​​
&​​)​ set_a = {1, 2,​
​ inds only the elements that are present in both sets.​​<br>​​
F
3}​
​ ​<br>​​
set_b = {3, 4, 5}​ ​<br>​​
set_a & set_b​​results in​​{3}​
​.​

​Difference (​​
-​)​​ set_a =​
​ inds elements that are in the first set but not in the second set.​​<br>​​
F
{1, 2, 3}​
​ ​<br>​​
set_b = {3, 4, 5}​ ​<br>​​
set_a - set_b​​results​​in​​{1, 2}​
​.​

​ ymmetric Difference​ F
S set_a = {1, 2,​
​ inds elements that are in one set or the other, but not both.​​<br>​​
​(​​
^​​)​ 3}​
​ ​<br>​​
set_b = {3, 4, 5}​ ​<br>​​
set_a ^ set_b​​results in​​
{1, 2, 4, 5}​ ​.​

​Having explored collections that store individual items, we now turn to a data structure designed to store data in pairs: the dictionary.​

​6.0 The Dictionary (​​


dict​
​): Mutable Key-Value Mappings​
I​n many programming scenarios, we need to look up data not by a numeric position, but by a meaningful label, such as a name or an​
dict​
​ID. How does Python solve this problem with high efficiency? The answer lies in the dictionary, or​​ ​, Python's​​implementation of a​
​hash map. Dictionaries are optimized for incredibly fast data retrieval based on a custom "key," making them the ideal choice for storing​
​and looking up data that is naturally paired.​

​6.1 Definition and Characteristics​


​ ​​dictionary​​is a collection of​​key-value pairs​​. Each​​key is unique and is used to look up its corresponding value. Its core​
A
​characteristics are:​

​1.​ ​Mutable​​: You can add, remove, and change key-value​​pairs after the dictionary is created.​
​2.​ O ​ rdered (Modern Python)​​: As of Python 3.7+, dictionaries preserve the order in which items were inserted. In older versions,​
​they were unordered. For exams, it is safe to mention this modern behavior.​
​3.​ ​Unique, Immutable Keys​​: The keys within a dictionary​​must be unique. They must also be of an immutable type (e.g., string,​
​number, or tuple). Values, however, can be of any type and can be duplicated.​

​6.2 Dictionary Creation and Manipulation​


{}​
​Dictionaries are created using curly braces​​ :​
​, with​​key-value pairs separated by a colon​​ ​.​

​ Creating a simple dictionary​


#
​student = {'name': 'Alice', 'id': 12345, 'major': 'Physics'}​

​ Accessing a value by its key​


#
​print(student['name']) # Output: Alice​

​ Adding a new key-value pair​


#
​student['year'] = 3​
​# student is now {'name': 'Alice', 'id': 12345, 'major': 'Physics', 'year': 3}​

​ Updating an existing value​


#
​student['major'] = 'Computer Science'​
​# student's major is now 'Computer Science'​

​ Deleting a key-value pair​


#
​del student['id']​
​# The 'id' key-value pair is removed​

​6.3 Essential Dictionary Methods​


​Dictionaries provide methods to efficiently work with their keys, values, and pairs.​

​Method​ ​Return Value​ ​Example Usage​

.keys()​
​ ​ view object displaying a list of all the keys​
A ​ist([Link]())​​results in​​
l ['name',​
​in the dictionary.​ 'major', 'year']​

.values()​
​ ​ view object displaying a list of all the​
A ​ist([Link]())​​results in​
l
​values in the dictionary.​ ['Alice', 'Computer Science', 3]​

.items()​
​ ​ view object displaying a list of key-value​
A ​ist([Link]())​​results in​​
l [('name',​
​tuple pairs.​ 'Alice'), ('major', 'Computer​

Science'), ('year', 3)]​

​get(key,​
. key​
​ eturns the value for​​
R key​​is not​
​. If​​ ​[Link]('gpa', 'N/A')​​returns​​
s 'N/A'​
default)​
​ default​​(or​​
​found, it returns​​ None​​if​ ​because 'gpa' key does not exist.​
default​​is omitted) instead of raising a​

KeyError​
​ ​.​

​ ith a firm grasp of each individual collection type, it is now time to consolidate our knowledge and perform a direct comparison to​
W
​guide our selection process.​
​7.0 Comparative Analysis of Python Collections​
​ hoosing the correct data structure is one of the most important decisions a programmer makes. The choice can significantly impact a​
C
​program's performance, readability, and correctness. This section provides a consolidated, at-a-glance reference to help you decide​
​which collection to use for a given problem—a critical skill frequently tested in programming exams.​

​Characteristic​ ​String​ ​List​ ​Tuple​ ​Set​ ​Dictionary​

​Mutability​ ​Immutable​ ​Mutable​ ​Immutable​ ​Mutable​ ​Mutable​

​Ordering​ ​Ordered​ ​Ordered​ ​Ordered​ ​Unordered​ ​ rdered (Python​


O
​3.7+)​

​Indexing​ ​Integer index​ ​Integer index​ ​Integer index​ ​Not applicable​ ​Key-based​

​ llows​
A ​Yes​ ​Yes​ ​Yes​ ​No​ ​No (for keys)​
​Duplicates?​

​Creation Syntax​ ''​​or​​


​ ""​ []​
​ ()​
​ set()​
​ {}​

​ rimary​
P ​ toring and​
S ​​
A ​Protecting data​ ​ nsuring​
E ​ ast lookups​
F
​Use-Case​ ​manipulating textual​ ​general-purpose​ ​integrity; use as​ ​uniqueness and​ ​based on​
​data.​ ​, flexible​ ​ ict keys.​
d ​math operations.​ ​key-value​
​sequence.​ ​mapping.​

I​n summary, the key decision points for selecting a data structure can be framed as a series of questions. If you need to store an​
​ordered sequence of items that can be changed, use a​​List​​. If that data should be fixed and never change,​​use a​​Tuple​​. If you only​
​need to know whether an item exists in a collection and do not care about order or duplicates, use a​​Set​​. Finally, if you need to store​
​and retrieve data based on a unique identifier or label, use a​​Dictionary​​.​

​With this theoretical framework established, we now turn to applying these collections to solve practical problems.​

​8.0 Practical Programs for Exam Preparation​


​ his section provides fully-worked examples of Python programs that solve common problems using the collections we have discussed.​
T
​These programs are designed to serve as models for answers to 10- and 15-mark practical exam questions, demonstrating proper​
​structure, commenting, and application of the correct data structures.​

​8.1 String Manipulation: Word and Vowel Counter​


​# Program to count words, vowels, and consonants in a user-provided sentence.​

​ Define the set of vowels for efficient membership checking.​


#
​# Using a set is optimal for 'in' checks, connecting this program to Section 5.0.​
​VOWELS = {'a', 'e', 'i', 'o', 'u'}​

​ 1. Take a sentence as input from the user.​


#
​sentence = input("Please enter a sentence: ")​
​ Initialize counters for our metrics.​
#
​word_count = 0​
​vowel_count = 0​
​consonant_count = 0​

​ 2. Use string methods to process the input.​


#
​# Convert the sentence to lowercase to make vowel checking case-insensitive.​
​sentence_lower = [Link]()​

​ Use the split() method to get a list of words. The length of this list is the word count.​
#
​words = [Link]()​
​word_count = len(words)​

​ 3. Iterate through each character to count vowels and consonants.​


#
​for char in sentence_lower:​
​# Use the isalpha() method to ensure we only count letters.​
​if [Link]():​
​# Check for membership in our VOWELS set.​
​if char in VOWELS:​
​vowel_count += 1​
​else:​
​consonant_count += 1​

​ 4. Print the results in a clear, formatted way.​


#
​print("\n--- Analysis Complete ---")​
​print(f"Original Sentence: {sentence}")​
​print(f"Number of Words: {word_count}")​
​print(f"Number of Vowels: {vowel_count}")​
​print(f"Number of Consonants: {consonant_count}")​
​print("-------------------------\n")​

​8.2 Dictionary Application: Simple Phonebook​


​# Program to implement a simple interactive phonebook using a dictionary.​

​def display_menu():​
​"""Prints the main menu of options for the user."""​
​print("\n--- Simple Phonebook Menu ---")​
​print("1. Look up a contact")​
​print("2. Add a new contact")​
​print("3. Delete a contact")​
​print("4. Exit")​
​print("-----------------------------\n")​

​ 1. Use a dictionary to store names (keys) and phone numbers (values).​


#
​phonebook = {​
​"Alice": "555-1234",​
​"Bob": "555-5678",​
​"Charlie": "555-9999"​
​}​

​ 2. Implement a simple loop that runs until the user chooses to exit.​
#
​while True:​
​display_menu()​
​choice = input("Enter your choice (1-4): ")​

​if choice == '1':​


​# Look up a contact​
​name = input("Enter the name to look up: ")​
​# Use the .get() method to handle cases where the name is not found.​
​number = [Link](name, "Contact not found.")​
​print(f"Result: {name}'s number is {number}")​

​elif choice == '2':​


​# Add a new contact​
​name = input("Enter the new contact's name: ")​
​number = input(f"Enter {name}'s phone number: ")​
​ honebook[name] = number​
p
​print(f"Contact '{name}' added successfully.")​

​elif choice == '3':​


​# Delete a contact​
​name = input("Enter the name to delete: ")​
​if name in phonebook:​
​del phonebook[name]​
​print(f"Contact '{name}' deleted successfully.")​
​else:​
​print(f"Error: Contact '{name}' not found.")​

​elif choice == '4':​


​# Exit the program​
​print("Exiting phonebook. Goodbye!")​
​break​

​else:​
​# Handle invalid menu choices​
​print("Invalid choice. Please enter a number between 1 and 4.")​

​8.3 Set Operations: Analyzing Student Club Memberships​


​# Program to analyze student club memberships using set operations.​

​ 1. Define two lists of student names representing members of two clubs.​


#
​coding_club_members = ["Alice", "Bob", "Charlie", "David", "Eve"]​
​robotics_club_members = ["Charlie", "Frank", "Grace", "Alice", "Heidi"]​

​ rint(f"Coding Club: {coding_club_members}")​


p
​print(f"Robotics Club: {robotics_club_members}\n")​

​ 2. Convert these lists to sets to leverage set operations.​


#
​# This automatically handles any duplicates within the original lists.​
​coding_set = set(coding_club_members)​
​robotics_set = set(robotics_club_members)​

​# 3. Use set operations to find and print the required information.​

​ a) Students who are in both clubs (intersection)​


#
​both_clubs = coding_set.intersection(robotics_set)​
​print(f"Students in both clubs: {both_clubs}")​

​ b) All unique students across both clubs (union)​


#
​all_students = coding_set.union(robotics_set)​
​print(f"All unique students in either club: {all_students}")​

​ c) Students who are only in the Coding Club but not the Robotics Club (difference)​
#
​only_coding = coding_set.difference(robotics_set)​
​print(f"Students only in the Coding Club: {only_coding}")​

​ d) Students who are in either club, but not both (symmetric difference)​
#
​either_not_both = coding_set.symmetric_difference(robotics_set)​
​print(f"Students in one club but not both: {either_not_both}")​

You might also like