Give an example of a list comprehension in Python.
💡 Model Answer
List comprehensions are a concise way to create lists in Python. They consist of an expression followed by a for clause, optionally followed by one or more if clauses. For example, to generate a list of even numbers from 0 to 18, you can write: evens = [x for x in range(19) if x % 2 == 0]. This single line replaces a for loop and an if statement. You can also include nested comprehensions, such as flattening a matrix: flat = [item for row in matrix for item in row]. List comprehensions are generally faster than equivalent loops because they are optimized in C. However, they can become hard to read if the expression is complex or if there are many nested loops. In such cases, a regular for loop or a generator expression may be clearer. Remember that list comprehensions create the entire list in memory, so for very large data sets consider using generator expressions with parentheses or itertools to avoid memory overhead.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500