micheledpierri.com

  • HOME
    • Python
    • Statistics
    • Data Analysis
    • Machine Learning
  • WRITINGS
  • VISIONS
  • ABOUT
Home / Python / Intermediate Python: Writing Clean, Pythonic Code
Children dressed in lab coats are studying a python

Intermediate Python: Writing Clean, Pythonic Code

Lesson Objectives

By the end of this lesson, you will be able to:

  • Write concise and readable Python code
  • Use list comprehensions instead of verbose loops
  • Understand and apply lambda functions
  • Use args and *kwargs to write flexible functions
  • Recognize what “Pythonic” code means in practice

This lesson completes the transition:

from writing Python that works to writing Python that is clean, expressive, and scalable.


1️⃣ What Does “Pythonic” Mean

“Pythonic” code is:

  • readable
  • concise
  • explicit
  • idiomatic

Python favors clarity over cleverness.

Rule of thumb:

If code is hard to read, it is probably not Pythonic.


2️⃣ List Comprehensions

List comprehensions provide a compact syntax for creating lists.

Classic Loop

squares = []
for x in range(5):
    squares.append(x ** 2)

List Comprehension

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

Same result, clearer intent.

With Conditions

even_numbers = [x for x in range(10) if x % 2 == 0]

This pattern is ubiquitous in data preprocessing.


3️⃣ Why List Comprehensions Matter in Data Analysis

They allow you to:

  • transform data cleanly
  • filter observations
  • express logic in one readable line

They also reduce boilerplate and error-prone code.


4️⃣ Lambda Functions

Lambda functions are anonymous, one-line functions.

Standard Function

def square(x):
    return x ** 2

Lambda Version

square = lambda x: x ** 2

Use lambdas when:

  • logic is simple
  • function is used briefly

Avoid lambdas for complex logic.


5️⃣ Lambdas in Practice

Common use case: transformation functions.

values = [1, 2, 3]
squared = list(map(lambda x: x ** 2, values))

Later, this idea appears in:

  • pandas.apply
  • feature transformations
  • model pipelines

6️⃣ args: Variable Positional Arguments

  • args allows functions to accept any number of positional arguments.
def add_all(*args):
    return sum(args)

Usage:

add_all(1, 2, 3, 4)

This increases flexibility without sacrificing clarity.


7️⃣ *kwargs: Variable Keyword Arguments

  • *kwargs allows functions to accept named arguments.
def describe_person(**kwargs):
    for key, value in kwargs.items():
        print(key, value)

Usage:

describe_person(name="Michele", age=40)

This is extremely common in libraries and frameworks.


8️⃣ Why args and *kwargs Matter

They allow you to:

  • write extensible APIs
  • forward arguments
  • build configurable functions

In machine learning libraries, almost everything relies on them.


9️⃣ Putting It All Together

Example combining multiple concepts:

def transform(values, func):
    return [func(x) for x in values]

transform([1, 2, 3], lambda x: x * 2)

This is a functional programming pattern that appears constantly in data science.


FAQ — Frequently Asked Questions

Q: Are list comprehensions always better than loops?

A: No. Use them when they improve readability.

Q: Are lambda functions faster?

A: No. They are about conciseness, not speed.

Q: Is *args required?

A: No, but it makes functions more flexible.

Q: What is the biggest Python mistake at this stage?

A: Writing overly clever code that nobody can read.


Exercises

Exercise 1

Create a list of squares from 0 to 9 using a list comprehension.

Exercise 2

Create a list of odd numbers from 0 to 20.

Exercise 3

Rewrite a for loop as a list comprehension.

Exercise 4

Write a lambda function that cubes a number.

Exercise 5

Use map with a lambda to double values in a list.

Exercise 6

Write a function using *args that computes the mean.

Exercise 7

Write a function using **kwargs that prints key-value pairs.

Exercise 8

Predict the output:

f = lambda x: x + 1
print(f(3))

Exercise 9

Explain when lambda functions should be avoided.

Exercise 10

Explain what “Pythonic” code means.


Solutions

Exercise 1

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

Exercise 2

odds = [x for x in range(21) if x % 2 != 0]

Exercise 3

# Loop version
# squares = []
# for x in range(5):
#     squares.append(x ** 2)

# Comprehension
squares = [x ** 2 for x in range(5)]

Exercise 4

cube = lambda x: x ** 3

Exercise 5

values = [1, 2, 3]
doubled = list(map(lambda x: x * 2, values))

Exercise 6

def mean(*args):
    return sum(args) / len(args)

Exercise 7

def show(**kwargs):
    for k, v in kwargs.items():
        print(k, v)

Exercise 8

# Output: 4

Exercise 9

# When logic becomes complex or hard to read

Exercise 10

# Pythonic code is readable, explicit, and idiomatic


Course Wrap-Up

You now have:

  • a solid Python foundation
  • the ability to read and write clean code
  • the conceptual tools required for:
    • statistics
    • data analysis
    • machine learning

From here on, Python stops being the subject and becomes the instrument.

Cite this article

Pierri, M. D. (2026). Intermediate Python: Writing Clean, Pythonic Code. micheledpierri.com. Permalink

Share:Email·LinkedIn
Previous← Object-Oriented Programming (OOP) in PythonNextPython Wrap-Up Lesson: A Mini Cardiology Risk-Factor Audit (Step-by-Step) →
Python
  1. Why Python
  2. Python & VS Code Setup (From Zero to a Professional Environment)
  3. Variables, Naming Rules, and Basic Syntax
  4. Core Data Types in Python
  5. Control Flow: Conditions and Loops
  6. Functions and Code Reusability
  7. Collections: Lists, Tuples, Sets, and Dictionaries
  8. Modules, Packages, and File Handling
  9. Errors, Exceptions, and Robust Code
  10. Object-Oriented Programming (OOP) in Python
  11. Intermediate Python: Writing Clean, Pythonic Code
  12. Python Wrap-Up Lesson: A Mini Cardiology Risk-Factor Audit (Step-by-Step)
© 2024–2026 micheledpierri.com · Privacy Policy · Impressum