
Chapter Outline
Chapter 3: Data Handling in Python
In this chapter, we explore Python’s core data types and collections. Understanding how Python represents and manipulates data is essential before moving into more advanced programming. We’ll cover:
- Primitive data types: strings, numbers, booleans
- Built-in collections: lists, tuples, sets, dictionaries
- Iterators and comprehensions for concise, efficient data processing
- A practical project: Contact Book, applying everything together
3.1 Primitive Data Types
Strings
pythonname = "Walid"greeting = f"Hello, {name}!"print(greeting) # Hello, Walid
Strings are immutable sequences of characters. Common operations:
pythons = "Python"print(len(s)) # 6print(s.upper()) # "PYTHON"print(s[0:3]) # "Pyt"
Numbers
python# Integersx = 42# Floatsy = 3.14# Complex numbersz = 2 + 3j
Python supports arbitrary-precision integers, so no overflow like in C or Java.
Booleans
pythonis_valid = Trueprint(is_valid and False) # False
3.2 Collections
Lists
Mutable, ordered, allow duplicates.
pythonfruits = ["apple", "banana", "cherry"]fruits.append("orange")print(fruits) # ['apple', 'banana', 'cherry', 'orange']
Tuples
Immutable, ordered.
pythonpoint = (10, 20)x, y = point # unpacking
Sets
Unordered, unique items.
pythonnums = {1, 2, 3, 3}print(nums) # {1, 2, 3}
Dictionaries
Key-value mappings.
pythonperson = {"name": "Alice", "age": 30}print(person["name"]) # Alice
3.3 Iterators and Comprehensions
Iterators
Any object that implements __iter__ and __next__.
pythonnums = [1, 2, 3]it = iter(nums)print(next(it)) # 1print(next(it)) # 2
List Comprehensions
Concise way to build lists.
pythonsquares = [x**2 for x in range(5)]print(squares) # [0, 1, 4, 9, 16]
Set & Dict Comprehensions
pythonunique_lengths = {len(w) for w in ["hi", "hello", "hi"]}print(unique_lengths) # {2, 5}word_map = {w: len(w) for w in ["hi", "hello"]}print(word_map) # {'hi': 2, 'hello': 5}
3.4 Project: Contact Book
We’ll build a simple CLI-based Contact Book that demonstrates strings, dicts, lists, and comprehensions.
contact_book.py1"""A simple Contact Book project demonstrating Python data handling."""23def add_contact(contacts: dict, name: str, phone: str, email: str) -> None:4 """Add a new contact to the dictionary."""5 contacts[name] = {"phone": phone, "email": email}678def search_contact(contacts: dict, name: str) -> dict | None:9 """Search for a contact by name."""10 return contacts.get(name)111213def list_contacts(contacts: dict) -> list[str]:14 """Return a formatted list of all contacts."""15 return [f"{name}: {info['phone']} / {info['email']}" for name, info in contacts.items()]161718if __name__ == "__main__":19 contacts: dict[str, dict[str, str]] = {}2021 add_contact(contacts, "Alice", "123-456", "alice@example.com")22 add_contact(contacts, "Bob", "555-555", "bob@example.com")2324 print("All contacts:")25 for line in list_contacts(contacts):26 print(" ", line)2728 print("\nSearch result:")29 result = search_contact(contacts, "Alice")30 print(result if result else "Not found")
Output
bashAll contacts:Alice: 123-456 / alice@example.comBob: 555-555 / bob@example.comSearch result:{'phone': '123-456', 'email': 'alice@example.com'}
Summary
- Strings, numbers, and booleans form the primitive building blocks of Python programs.
- Lists, tuples, sets, and dictionaries are core data structures.
- Iterators and comprehensions make code concise and expressive.
- Practical application: the Contact Book combines multiple data structures for a real-world use case.
Check your understanding
Test your knowledge of Data Handling in Python