Python #4 Strings & Collections

CS25C02 · COMPUTER PROGRAMMING: PYTHON

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.

17Core topics
05Practical programs
12Quiz questions
0 / 17Topics completed
YOUR LEARNING PATH

Choose a topic ๐ŸŒŸ

Read the notes, trace the example, and try each mini task before moving on.

๐Ÿ”ค
TOPIC 01

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?

⚖️
TOPIC 02

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?

๐Ÿงต
TOPIC 03

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.

✂️
TOPIC 04

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"?

๐Ÿช“
TOPIC 05

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.

๐Ÿงฝ
TOPIC 06

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?

๐Ÿ“‹
TOPIC 07

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?

๐Ÿ“ฆ
TOPIC 08

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?

๐Ÿ—‚️
TOPIC 09

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"}?

➕
TOPIC 10

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?

๐Ÿ”Ž
TOPIC 11

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?

↕️
TOPIC 12

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?

๐Ÿ“
TOPIC 13

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?

➕
TOPIC 14

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.

➖
TOPIC 15

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?

๐Ÿ”‘
TOPIC 16

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?

๐Ÿ”„
TOPIC 17

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?

LEARN BY DOING

Interactive Python practical lab ๐Ÿงช

Five practicals are included, exceeding the minimum of three. Edit the code and run it in your browser.

PRACTICAL 01

String manipulations

Clean, split, slice, compare, and format text.

PYTHON
Ready to run
OUTPUT
Click “Run Python” to execute this example.

The Python runtime loads on first use and needs an internet connection. Modify the code to experiment.

PRACTICAL 02

Operations on Lists

Append, update, search, and sort list values.

PYTHON
Ready to run
OUTPUT
Click “Run Python” to execute this example.

The Python runtime loads on first use and needs an internet connection. Modify the code to experiment.

PRACTICAL 03

Operations on Tuples

Create, index, unpack, and combine tuples.

PYTHON
Ready to run
OUTPUT
Click “Run Python” to execute this example.

The Python runtime loads on first use and needs an internet connection. Modify the code to experiment.

PRACTICAL 04

Operations on Sets

Use sets for unique values, union, intersection, and difference.

PYTHON
Ready to run
OUTPUT
Click “Run Python” to execute this example.

The Python runtime loads on first use and needs an internet connection. Modify the code to experiment.

PRACTICAL 05

Operations on Dictionaries

Create, access, add, update, and remove key-value pairs.

PYTHON
Ready to run
OUTPUT
Click “Run Python” to execute this example.

The Python runtime loads on first use and needs an internet connection. Modify the code to experiment.

CHECK YOUR UNDERSTANDING

Unit 4 quiz ๐Ÿง 

Answer all 12 questions, then check your score and read the explanations.

1. Which string method removes whitespace from both ends?

2. What does "Python"[1:4] return?

3. Which expression makes a formatted string?

4. What does split(",") return?

5. Which statement about lists is true?

6. How do you create a one-item tuple?

7. What does 2 in [1, 2, 3] evaluate to?

8. Which sorts a list in place?

9. What is a set mainly useful for?

10. How do you access the value for key "age" in d?

11. What does d.get("city", "Unknown") do if city is missing?

12. Which operation gives common elements of sets a and b?

Submit to reveal the correct answers and explanations.

YOUR LEARNING PROGRESS

Celebrate each step ๐Ÿ†

Tick each topic after reading the notes and attempting its mini task.

Unit IV progress0%

๐ŸŽฏ 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.

CONTINUE LEARNING

References & learning resources ๐Ÿ“š

CS25C02 · Unit IV: Strings and Collections · Interactive Python Study Hub

Comments

Popular posts from this blog

index.html

Python #1 Fundamentals

#Python YT Videos for Jamal Engineering Students