1. Home
  2. Coding Hub
  3. Coding Notes
  4. Python
  5. List Comprehensions
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
01Hrs
13Mins
40Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Python
  5. List Comprehensions

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
01Hrs
13Mins
40Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
Python IntroductionInterpreter & BytecodeSyntax & IndentationDynamic VariablesPrimitive TypesType CastingInput & Output
Arithmetic OperatorsLogical & Bitwise Operatorsis vs ==if / elsematch / casefor Loopswhile LoopsLoop Control (break, continue)
String IndexingString SlicingString MethodsF-StringsRegex Basics
List BasicsList OperationsList ComprehensionsTuplesSetsDictionary BasicsDictionary MethodsDict Comprehensionscollections Moduleheapq & bisectUnpacking Operators (*, **)
Function Basics*args & **kwargsLEGB ScopeLambda Functionsmap, filter, zipClosuresDecoratorsType Hinting
Classes & Objects__init__ & selfClass Methods & Static MethodsInheritance & super()Duck TypingEncapsulation & PropertiesDunder MethodsData Classes
Memory ManagementShallow vs Deep Copytry / exceptCustom ExceptionsContext Managers (with)File & JSON Operations
IteratorsGenerators & yieldVirtual EnvironmentsGIL & Threadingasyncio Basics
Python

List Comprehensions

Overview

List comprehensions are a defining feature of Pythonic code. They provide a concise, readable, and highly optimized syntax to create a new list by transforming or filtering an existing iterable. In standard loops, you must declare an empty list and call .append() repeatedly. List comprehensions accomplish this in a single line. Furthermore, because they are implemented directly in C under the hood, they execute significantly faster than equivalent standard for loops.

Syntax

python
nums = [1, 2, 3, 4, 5]

# The standard (slower) loop approach:
squares = []
for n in nums:
    squares.append(n ** 2)

# The List Comprehension approach:
# Syntax: [expression for item in iterable if condition]
squares = [n ** 2 for n in nums]

# Comprehension with a filtering condition (Only even numbers)
even_squares = [n ** 2 for n in nums if n % 2 == 0]

# Nested comprehension (Flattening a 2D matrix)
matrix = [[1, 2], [3, 4]]
flat = [num for row in matrix for num in row] # [1, 2, 3, 4]

Common Pitfalls

  • Over-engineering. If a list comprehension becomes so complex that it spans multiple lines and contains complex nested loops, it destroys readability. Use a standard loop in these cases.
  • Forgetting that list comprehensions eagerly evaluate. If you run [x for x in range(10_000_000)], it will immediately generate and store 10 million items in RAM, likely crashing the system. Use a Generator instead.

Interview Questions

Why are list comprehensions faster than standard for-loops?

List comprehensions do not need to look up the list object and invoke the .append() method on every iteration. The memory allocation and appending logic are handled directly at the C-level.

Real-World Example

Extracting specific fields from a list of complex dictionaries (a very common API response pattern).

example
python
users = [
    {"name": "Alice", "status": "active"},
    {"name": "Bob", "status": "inactive"},
    {"name": "Charlie", "status": "active"}
]

# Cleanly extract only the names of active users
active_names = [user["name"] for user in users if user["status"] == "active"]
print(active_names) # ['Alice', 'Charlie']

Check Your Knowledge

Test your understanding of List Comprehensions with these quick questions.

Question 1

Which of the following creates a list of zeroes exactly 5 elements long?

Take Python Quiz
Outline
Python IntroductionInterpreter & BytecodeSyntax & IndentationDynamic VariablesPrimitive TypesType CastingInput & Output
Arithmetic OperatorsLogical & Bitwise Operatorsis vs ==if / elsematch / casefor Loopswhile LoopsLoop Control (break, continue)
String IndexingString SlicingString MethodsF-StringsRegex Basics
List BasicsList OperationsList ComprehensionsTuplesSetsDictionary BasicsDictionary MethodsDict Comprehensionscollections Moduleheapq & bisectUnpacking Operators (*, **)
Function Basics*args & **kwargsLEGB ScopeLambda Functionsmap, filter, zipClosuresDecoratorsType Hinting
Classes & Objects__init__ & selfClass Methods & Static MethodsInheritance & super()Duck TypingEncapsulation & PropertiesDunder MethodsData Classes
Memory ManagementShallow vs Deep Copytry / exceptCustom ExceptionsContext Managers (with)File & JSON Operations
IteratorsGenerators & yieldVirtual EnvironmentsGIL & Threadingasyncio Basics
Python

List Comprehensions

Overview

List comprehensions are a defining feature of Pythonic code. They provide a concise, readable, and highly optimized syntax to create a new list by transforming or filtering an existing iterable. In standard loops, you must declare an empty list and call .append() repeatedly. List comprehensions accomplish this in a single line. Furthermore, because they are implemented directly in C under the hood, they execute significantly faster than equivalent standard for loops.

Syntax

python
nums = [1, 2, 3, 4, 5]

# The standard (slower) loop approach:
squares = []
for n in nums:
    squares.append(n ** 2)

# The List Comprehension approach:
# Syntax: [expression for item in iterable if condition]
squares = [n ** 2 for n in nums]

# Comprehension with a filtering condition (Only even numbers)
even_squares = [n ** 2 for n in nums if n % 2 == 0]

# Nested comprehension (Flattening a 2D matrix)
matrix = [[1, 2], [3, 4]]
flat = [num for row in matrix for num in row] # [1, 2, 3, 4]

Common Pitfalls

  • Over-engineering. If a list comprehension becomes so complex that it spans multiple lines and contains complex nested loops, it destroys readability. Use a standard loop in these cases.
  • Forgetting that list comprehensions eagerly evaluate. If you run [x for x in range(10_000_000)], it will immediately generate and store 10 million items in RAM, likely crashing the system. Use a Generator instead.

Interview Questions

Why are list comprehensions faster than standard for-loops?

List comprehensions do not need to look up the list object and invoke the .append() method on every iteration. The memory allocation and appending logic are handled directly at the C-level.

Real-World Example

Extracting specific fields from a list of complex dictionaries (a very common API response pattern).

example
python
users = [
    {"name": "Alice", "status": "active"},
    {"name": "Bob", "status": "inactive"},
    {"name": "Charlie", "status": "active"}
]

# Cleanly extract only the names of active users
active_names = [user["name"] for user in users if user["status"] == "active"]
print(active_names) # ['Alice', 'Charlie']

Check Your Knowledge

Test your understanding of List Comprehensions with these quick questions.

Question 1

Which of the following creates a list of zeroes exactly 5 elements long?

Take Python Quiz

Python coding notes for Indian students — 58 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Python

  1. Python Introduction
  2. Interpreter & Bytecode
  3. Syntax & Indentation
  4. Dynamic Variables
  5. Primitive Types
  6. Type Casting
  7. Input & Output
  8. Arithmetic Operators
  9. Logical & Bitwise Operators
  10. is vs ==
  11. if / else
  12. match / case
  13. for Loops
  14. while Loops
  15. Loop Control (break, continue)
  16. String Indexing
  17. String Slicing
  18. String Methods
  19. F-Strings
  20. Regex Basics
  21. List Basics
  22. List Operations
  23. List Comprehensions
  24. Tuples
  25. Sets
  26. Dictionary Basics
  27. Dictionary Methods
  28. Dict Comprehensions
  29. collections Module
  30. heapq & bisect
  31. Unpacking Operators (*, **)
  32. Function Basics
  33. *args & **kwargs
  34. LEGB Scope
  35. Lambda Functions
  36. map, filter, zip
  37. Closures
  38. Decorators
  39. Type Hinting
  40. Classes & Objects
  41. __init__ & self
  42. Class Methods & Static Methods
  43. Inheritance & super()
  44. Duck Typing
  45. Encapsulation & Properties
  46. Dunder Methods
  47. Data Classes
  48. Memory Management
  49. Shallow vs Deep Copy
  50. try / except
  51. Custom Exceptions
  52. Context Managers (with)
  53. File & JSON Operations
  54. Iterators
  55. Generators & yield
  56. Virtual Environments
  57. GIL & Threading
  58. asyncio Basics

Study next

  • All coding notes
  • Python notes home
  • Python certification quiz
  • Online compiler
  • Interview Q&A

Python coding notes for Indian students — 58 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Python

  1. Python Introduction
  2. Interpreter & Bytecode
  3. Syntax & Indentation
  4. Dynamic Variables
  5. Primitive Types
  6. Type Casting
  7. Input & Output
  8. Arithmetic Operators
  9. Logical & Bitwise Operators
  10. is vs ==
  11. if / else
  12. match / case
  13. for Loops
  14. while Loops
  15. Loop Control (break, continue)
  16. String Indexing
  17. String Slicing
  18. String Methods
  19. F-Strings
  20. Regex Basics
  21. List Basics
  22. List Operations
  23. List Comprehensions
  24. Tuples
  25. Sets
  26. Dictionary Basics
  27. Dictionary Methods
  28. Dict Comprehensions
  29. collections Module
  30. heapq & bisect
  31. Unpacking Operators (*, **)
  32. Function Basics
  33. *args & **kwargs
  34. LEGB Scope
  35. Lambda Functions
  36. map, filter, zip
  37. Closures
  38. Decorators
  39. Type Hinting
  40. Classes & Objects
  41. __init__ & self
  42. Class Methods & Static Methods
  43. Inheritance & super()
  44. Duck Typing
  45. Encapsulation & Properties
  46. Dunder Methods
  47. Data Classes
  48. Memory Management
  49. Shallow vs Deep Copy
  50. try / except
  51. Custom Exceptions
  52. Context Managers (with)
  53. File & JSON Operations
  54. Iterators
  55. Generators & yield
  56. Virtual Environments
  57. GIL & Threading
  58. asyncio Basics

Study next

  • All coding notes
  • Python notes home
  • Python certification quiz
  • Online compiler
  • Interview Q&A