Q1. What is list comprehension in Python?
List comprehension provides a concise way to create lists based on existing lists. Syntax:
[expression for item in iterable if condition] Example: squares = [x**2 for x in range(10)]Q2. What are the advantages of list comprehensions?
List comprehensions are more compact and often faster than traditional for loops because they are optimized in Python's C implementation. They reduce boilerplate code and improve readability for simple transformations.
Q3. Can you use nested list comprehensions?
Yes, nested loops can be expressed in list comprehensions. Example:
matrix = [[j for j in range(5)] for i in range(3)] This creates a 3x5 matrix. Order of loops corresponds to nesting.Q4. What is dictionary and set comprehension?
Similar to list comprehension, dictionary comprehension uses curly braces with key:value. Set comprehension uses curly braces for unique values. Example:
squares_dict = {x: x**2 for x in range(5)}
even_set = {x for x in range(10) if x % 2 == 0}Q5. When should you avoid list comprehensions?
Avoid list comprehensions when the logic is complex (nested loops with multiple conditions) as readability suffers. Use traditional for loops for clarity. Also, if you only need an iterator, consider generator expressions for memory efficiency.
