Day 6 - Python Interview Questions

Topic: List Comprehension & Lambda

Below are some interview-style coding questions to test your understanding of list comprehensions and lambda functions.

1. Odd Number Squares

Using a list comprehension, generate the squares of all odd numbers from 1 to 15.

# Expected Output:
# [1, 9, 25, 49, 81, 121, 169, 225]

2. Filter Strings by Length

Given a list of words, use filter() and lambda to return words with length greater than 4.

# Example: ["cat", "elephant", "dog", "giraffe"] → ["elephant", "giraffe"]

3. Tuple to Dictionary

Using a dictionary comprehension, convert a list of tuples into a dictionary.

# Example: [("a", 1), ("b", 2)] → {"a": 1, "b": 2}

4. Common Elements

Given two lists, use a list comprehension to find the common elements.

# Example: [1, 2, 3, 4], [3, 4, 5] → [3, 4]

5. Sort by Last Character

Using sorted() and lambda, sort a list of words by their last character.

# Example: ["apple", "banana", "cherry"] → ["banana", "apple", "cherry"]

6. Flatten a List of Lists

Using a nested list comprehension, flatten a list of lists into a single list.

# Example: [[1, 2], [3, 4], [5]] → [1, 2, 3, 4, 5]