Intermediate Python: Unlocking Python’s Full Potential

Kolluru PawanKolluru Pawan
3 min read

Introduction

Now that you’ve mastered Python fundamentals, it’s time to level up! Intermediate Python introduces powerful tools and techniques to write cleaner, faster, and more efficient code.

In this blog, we’ll cover:
Lambda, map, filter, reduce
List/Dict/Set Comprehensions
Iterators & Generators
Modules & Packages
File I/O
Virtual Environments
Regular Expressions (re)
Type Hinting & mypy
Logging & Debugging
with Statement & Context Managers


1. Lambda, map, filter, reduce

Lambda (Anonymous Functions)

square = lambda x: x ** 2  
print(square(5))  # 25

map (Apply Function to All Elements)

numbers = [1, 2, 3]  
squared = list(map(lambda x: x ** 2, numbers))  
print(squared)  # [1, 4, 9]

filter (Select Elements Based on Condition)

even_numbers = list(filter(lambda x: x % 2 == 0, numbers))  
print(even_numbers)  # [2]

reduce (Cumulative Operation)

from functools import reduce  
sum_all = reduce(lambda a, b: a + b, numbers)  
print(sum_all)  # 6

2. List/Dict/Set Comprehensions

List Comprehension

squares = [x ** 2 for x in range(5)]  # [0, 1, 4, 9, 16]

Dict Comprehension

square_dict = {x: x ** 2 for x in range(5)}  # {0:0, 1:1, 2:4, 3:9, 4:16}

Set Comprehension

unique_squares = {x ** 2 for x in [-2, -1, 0, 1, 2]}  # {0, 1, 4}

3. Iterators & Generators

Iterators (Lazy Evaluation)

nums = iter([1, 2, 3])  
print(next(nums))  # 1  
print(next(nums))  # 2

Generators (yield for Memory Efficiency)

def count_up_to(n):  
    i = 1  
    while i <= n:  
        yield i  
        i += 1  

counter = count_up_to(3)  
print(list(counter))  # [1, 2, 3]

4. Modules & Packages

Importing Modules

import math  
print(math.sqrt(16))  # 4.0  

from datetime import datetime  
print(datetime.now())

Creating a Package

my_package/  
│  
├── __init__.py  
├── module1.py  
└── module2.py
# Import from package  
from my_package import module1

5. File I/O (Reading & Writing Files)

# Writing to a file  
with open("example.txt", "w") as file:  
    file.write("Hello, Python!")  

# Reading from a file  
with open("example.txt", "r") as file:  
    content = file.read()  
    print(content)  # "Hello, Python!"

6. Virtual Environments (venv)

Create & Activate

python -m venv myenv  
source myenv/bin/activate  # Linux/Mac  
myenv\Scripts\activate     # Windows

Install Packages

pip install requests numpy

7. Regular Expressions (re)

import re  

text = "Email me at user@example.com"  
match = re.search(r"[\w.-]+@[\w.-]+", text)  
print(match.group())  # "user@example.com"

8. Type Hinting & mypy

def greet(name: str) -> str:  
    return f"Hello, {name}"  

# Install mypy for static type checking  
# pip install mypy  
# mypy script.py

9. Logging & Debugging

Logging

import logging  

logging.basicConfig(level=logging.INFO)  
logging.info("This is an info message")

Debugging (pdb)

import pdb  

def buggy_function():  
    pdb.set_trace()  # Debugger starts here  
    x = 10 / 0

10. with Statement & Context Managers

File Handling (Auto-Closes File)

with open("file.txt", "r") as file:  
    data = file.read()

Custom Context Manager

class Timer:  
    def __enter__(self):  
        self.start = time.time()  

    def __exit__(self, *args):  
        print(f"Time taken: {time.time() - self.start} sec")  

with Timer():  
    time.sleep(2)  # Prints "Time taken: ~2.0 sec"

Conclusion

Mastering these intermediate Python concepts will make you a more efficient and skilled developer.

0
Subscribe to my newsletter

Read articles from Kolluru Pawan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Kolluru Pawan
Kolluru Pawan