Python Practice Set (Part 15): Pythonic Programming
- Anubhav Somani
- Sep 3
- 2 min read

Writing Elegant Code: A Guide to Pythonic Comprehensions, Lambdas, Map, and Filter
Welcome to Part 15 of our Python practice series! As you advance, you'll hear the term "Pythonic," which refers to code that is not just functional, but also clean, readable, and idiomatic to the Python language. This practice set focuses on four powerful tools that help you write more Pythonic code: List Comprehensions, Lambda Functions, map, and filter. These will allow you to perform complex operations on data with incredibly concise and elegant syntax.
1. Filtering with a List Comprehension
You have a list of numbers: numbers = [1, 10, 25, 30, 45, 52, 60, 71]. Create a new list called divisible_by_five that contains only the numbers from the original list that are divisible by 5. Solve this using a single-line list comprehension.
2. Conditional Logic in a List Comprehension
Using the same numbers list, create a new list of strings called number_labels. For each number in the original list, the new list should contain the string "Even" if the number is even, and "Odd" if the number is odd. Solve this using a single-line list comprehension with a conditional expression.
3. Sorting with a Lambda Function
You have a list of tuples, where each tuple contains a product name and its price: products = [('apple', 1.50), ('banana', 0.75), ('orange', 1.25)]. Your task is to sort this list based on the price (the second item in each tuple) in ascending order. Use the sort() method or sorted() function with a lambda function as the key.
4. Transforming Data with map
You have a list of names that are not consistently capitalized: names = ["alice", "BOB", "Charlie"]. Use the map()function along with a lambda to create a new list called capitalized_names where each name is properly capitalized (e.g., "Alice", "Bob", "Charlie").
Hint: The str.capitalize() method will be useful here.
5. Selecting Data with filter
You have a list of dictionaries, each representing a person: people = [ {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 17}, {'name': 'Charlie', 'age': 30}, {'name': 'David', 'age': 16} ] Use the filter()function with a lambda to create a new list called adults that contains only the dictionaries of people who are 18 years or older.
Lucky Link -https://amzn.to/4lXO9zo
Comments