Python #4 Strings & Collections
Unit 4: Strings & Collections
Master text processing and Python collections: compare, format, slice, split, and strip strings; build, search, sort, and update lists, tuples, sets, and dictionaries.
Choose a topic ๐
Read the notes, trace the example, and try each mini task before moving on.
Strings
A string is an immutable sequence of characters.
Read notes ↗String Comparison
Compare text values with comparison operators.
Read notes ↗String Formatting
Insert values into readable text.
Read notes ↗String Slicing
Extract a substring using start:stop:step.
Read notes ↗Splitting Strings
Split text into a list of pieces.
Read notes ↗Stripping Strings
Remove whitespace or selected edge characters.
Read notes ↗Lists
Store an ordered, mutable collection.
Read notes ↗Tuples
Store an ordered, immutable collection.
Read notes ↗Dictionaries
Map unique keys to values.
Read notes ↗Basic List Operators
Combine, repeat, and test list contents.
Read notes ↗Searching Lists
Check membership or find an item position.
Read notes ↗Sorting Lists
Arrange list items in ascending or descending order.
Read notes ↗Dictionary Literals
Create dictionaries using key:value pairs.
Read notes ↗Adding Dictionary Keys
Add a new key by assigning a value.
Read notes ↗Removing Dictionary Keys
Delete dictionary entries safely.
Read notes ↗Accessing Dictionary Values
Retrieve values using keys or get().
Read notes ↗Replacing Dictionary Values
Update the value associated with an existing key.
Read notes ↗Strings
A string is an immutable sequence of characters.
๐ Understand the idea
Strings are written inside quotes. Python provides methods and operators to inspect, combine, and transform text.
Remember
Strings are immutable: methods return a new string rather than changing the original.
Worked example
message = "Python"
print(message)
print(len(message))๐ง Exam quick notes
- Use single or double quotes.
- Indexing starts at 0.
- len(text) returns the number of characters.
✍️ Mini task
How can you find the length of a string?
String Comparison
Compare text values with comparison operators.
๐ Understand the idea
Strings can be compared with ==, !=, <, >, <=, and >=. Equality checks exact content; ordering is lexicographic and affected by character code/case.
Remember
"Python" == "python" is False because the letter case differs.
Worked example
print("cat" == "cat")
print("apple" < "banana")
print("Python" == "python")๐ง Exam quick notes
- Use == to test equality, not =.
- String ordering is lexicographic.
- Normalize case with lower() when a case-insensitive comparison is needed.
✍️ Mini task
Why are "Hello" and "hello" not equal?
String Formatting
Insert values into readable text.
๐ Understand the idea
F-strings let expressions appear inside braces. format() and percent formatting are alternatives, but f-strings are usually easiest to read.
Remember
Use f"...{expression}..." for clear interpolation.
Worked example
name = "Asha"
score = 87.5
print(f"{name} scored {score:.1f}%")๐ง Exam quick notes
- Expressions inside f-string braces are evaluated.
- Format specifiers can control decimal places.
- Use str() when explicitly converting a value to text.
✍️ Mini task
Write an f-string showing a name and mark.
String Slicing
Extract a substring using start:stop:step.
๐ Understand the idea
Slicing selects a range of characters. The start index is included and the stop index is excluded. Negative indexes count from the end.
Remember
text[start:stop] does not include the character at stop.
Worked example
word = "COMPUTER"
print(word[0:3])
print(word[3:])
print(word[-3:])๐ง Exam quick notes
- Omitted start defaults to the beginning.
- Omitted stop defaults to the end.
- A step can skip characters, e.g. text[::2].
✍️ Mini task
What does word[1:4] return for "PYTHON"?
Splitting Strings
Split text into a list of pieces.
๐ Understand the idea
The split() method divides a string at a separator. With no separator, consecutive whitespace is treated as a separator.
Remember
split() returns a list of strings.
Worked example
line = "red,green,blue"
colors = line.split(",")
print(colors)๐ง Exam quick notes
- Specify the delimiter when needed.
- split() without an argument splits on whitespace.
- Use join() to combine strings from a list.
✍️ Mini task
Split "one two three" into words.
Stripping Strings
Remove whitespace or selected edge characters.
๐ Understand the idea
strip() removes leading and trailing whitespace. lstrip() and rstrip() target one side. You can pass a set of characters to remove from the edges.
Remember
strip() does not remove spaces in the middle of a string.
Worked example
raw = " hello Python
"
print(raw.strip())
print("---title---".strip("-"))๐ง Exam quick notes
- Use strip() for user input cleanup.
- lstrip() removes from the left; rstrip() from the right.
- strip(chars) treats chars as a set, not as one exact substring.
✍️ Mini task
Which method removes trailing whitespace only?
Lists
Store an ordered, mutable collection.
๐ Understand the idea
Lists use square brackets and can contain values of different types. Items can be changed, added, or removed.
Remember
Lists are mutable and preserve order.
Worked example
numbers = [10, 20, 30]
numbers[1] = 99
numbers.append(40)
print(numbers)๐ง Exam quick notes
- Indexing starts at 0.
- append() adds one item at the end.
- Use len(list_name) to count items.
✍️ Mini task
How do you add 50 to the end of a list?
Tuples
Store an ordered, immutable collection.
๐ Understand the idea
Tuples are commonly written with parentheses. Their items cannot be reassigned after creation. A one-item tuple needs a trailing comma.
Remember
For one item, write ("red",), not ("red").
Worked example
point = (4, 7)
print(point[0])
print(len(point))
single = ("red",)
print(single)๐ง Exam quick notes
- Tuples support indexing and slicing.
- Tuples are immutable.
- Tuple unpacking can assign items to variables.
✍️ Mini task
Why does (5,) represent a tuple but (5) does not?
Dictionaries
Map unique keys to values.
๐ Understand the idea
A dictionary stores key-value pairs. Keys must be hashable; values can be any type. Access values by key rather than numeric position.
Remember
Dictionary keys are unique; assigning an existing key updates its value.
Worked example
student = {"name": "Mira", "mark": 91}
print(student["name"])
print(student.get("grade", "Not set"))๐ง Exam quick notes
- Create dictionaries with braces and key:value pairs.
- Use get() to avoid a KeyError for a missing key.
- keys(), values(), and items() provide useful views.
✍️ Mini task
What is the key in {"city": "Chennai"}?
Basic List Operators
Combine, repeat, and test list contents.
๐ Understand the idea
The + operator concatenates lists, * repeats a list, and in / not in test membership. Slicing extracts part of a list.
Remember
These operators create results; append() modifies a list in place.
Worked example
a = [1, 2]
b = [3, 4]
print(a + b)
print(a * 2)
print(2 in a)๐ง Exam quick notes
- Use + for concatenation.
- Use * for repetition.
- Use in to test membership.
✍️ Mini task
What is the result of [1, 2] * 2?
Searching Lists
Check membership or find an item position.
๐ Understand the idea
Use in to check whether a value exists and index() to find the first matching position. count() returns how often a value appears.
Remember
index() raises ValueError if the item is not present; check membership first if needed.
Worked example
items = ["pen", "book", "pen"]
print("book" in items)
print(items.index("pen"))
print(items.count("pen"))๐ง Exam quick notes
- in returns True or False.
- index() returns the first matching index.
- count() counts occurrences.
✍️ Mini task
Which method counts repeated values in a list?
Sorting Lists
Arrange list items in ascending or descending order.
๐ Understand the idea
sort() changes a list in place. sorted() returns a new sorted list and works with other iterables too. Use reverse=True for descending order.
Remember
sort() returns None; use the list after calling it.
Worked example
values = [8, 2, 5, 1]
print(sorted(values))
values.sort(reverse=True)
print(values)๐ง Exam quick notes
- sorted(values) preserves the original list.
- list.sort() modifies the list.
- Use key= for custom sorting criteria.
✍️ Mini task
Which operation returns a new sorted list?
Dictionary Literals
Create dictionaries using key:value pairs.
๐ Understand the idea
A dictionary literal uses braces, commas between pairs, and a colon between each key and value. Keys must be unique.
Remember
Use { } for an empty dictionary; {} is not an empty set.
Worked example
book = {"title": "Python Basics", "pages": 180}
empty = {}
print(book)
print(type(empty).__name__)๐ง Exam quick notes
- Each pair uses key: value.
- Keys must be hashable.
- Later duplicate keys replace earlier values.
✍️ Mini task
How do you write an empty dictionary?
Adding Dictionary Keys
Add a new key by assigning a value.
๐ Understand the idea
Assigning a value to a key that does not yet exist creates a new key-value pair. update() can add multiple pairs.
Remember
dictionary[new_key] = value adds or updates a pair.
Worked example
profile = {"name": "Ravi"}
profile["city"] = "Chennai"
profile.update({"year": 1})
print(profile)๐ง Exam quick notes
- Assignment adds a missing key.
- update() can add multiple pairs.
- Keys are unique.
✍️ Mini task
Add the key "age" with value 20 to a dictionary d.
Removing Dictionary Keys
Delete dictionary entries safely.
๐ Understand the idea
del dictionary[key] removes a key; pop(key) removes it and returns its value. pop() can accept a default to avoid an error when the key is absent.
Remember
pop() is useful when you also need the removed value.
Worked example
data = {"a": 1, "b": 2}
removed = data.pop("a")
print(removed)
print(data)๐ง Exam quick notes
- del d[key] raises KeyError if missing.
- d.pop(key, default) can handle a missing key.
- clear() removes all entries.
✍️ Mini task
Which method removes a key and returns its value?
Accessing Dictionary Values
Retrieve values using keys or get().
๐ Understand the idea
Square brackets return the value for a key but raise KeyError if absent. get() returns None or a chosen default when the key is missing.
Remember
Use get() when a key may not exist.
Worked example
person = {"name": "Leela", "age": 19}
print(person["name"])
print(person.get("city", "Unknown"))๐ง Exam quick notes
- d[key] accesses a required key.
- d.get(key) handles missing keys gracefully.
- Membership checks keys: key in d.
✍️ Mini task
What does d.get("missing", 0) return if the key is absent?
Replacing Dictionary Values
Update the value associated with an existing key.
๐ Understand the idea
Assigning to an existing key replaces its value. update() can update one or more entries.
Remember
A dictionary key remains unique when its value changes.
Worked example
marks = {"Anu": 78, "Bala": 82}
marks["Anu"] = 95
marks.update({"Bala": 88})
print(marks)๐ง Exam quick notes
- Use d[key] = new_value to replace.
- update() accepts another mapping or key-value pairs.
- The dictionary is modified in place.
✍️ Mini task
How do you change the value for key "score" in d to 100?
Interactive Python practical lab ๐งช
Five practicals are included, exceeding the minimum of three. Edit the code and run it in your browser.
String manipulations
Clean, split, slice, compare, and format text.
Click “Run Python” to execute this example.
The Python runtime loads on first use and needs an internet connection. Modify the code to experiment.
Operations on Lists
Append, update, search, and sort list values.
Click “Run Python” to execute this example.
The Python runtime loads on first use and needs an internet connection. Modify the code to experiment.
Operations on Tuples
Create, index, unpack, and combine tuples.
Click “Run Python” to execute this example.
The Python runtime loads on first use and needs an internet connection. Modify the code to experiment.
Operations on Sets
Use sets for unique values, union, intersection, and difference.
Click “Run Python” to execute this example.
The Python runtime loads on first use and needs an internet connection. Modify the code to experiment.
Operations on Dictionaries
Create, access, add, update, and remove key-value pairs.
Click “Run Python” to execute this example.
The Python runtime loads on first use and needs an internet connection. Modify the code to experiment.
Unit 4 quiz ๐ง
Answer all 12 questions, then check your score and read the explanations.
Celebrate each step ๐
Tick each topic after reading the notes and attempting its mini task.
๐ฏ Learning outcomes
By the end of Unit IV, you should be able to compare, format, slice, split, and strip strings; perform common list and tuple operations; use sets for unique values and set operations; and create, access, add, remove, and update dictionary entries.
References & learning resources ๐
- Python Tutorial — Strings (official Python docs) ↗
- Python Tutorial — Data Structures: Lists, Tuples, Sets, Dictionaries ↗
- Python Standard Types — Built-in Types and Operations ↗
Comments
Post a Comment