list comprehension
A compact Python expression that builds a new list by looping over items and optionally filtering them.
In more detail
It is written in square brackets, such as [x * 2 for x in numbers if x > 0], and reads as: the expression, for each item, optionally only if a condition holds. Braces give a set or, with key: value, a dictionary comprehension. When the logic needs several statements or side effects, a plain loop is clearer.
Examples
failed = [d for d in deploys if d["tag"] in remediations][w.upper() for w in words if len(w) > 3]Related terms
- Python — A popular general-purpose programming language known for readable code and a large standard library.
- for loop — A loop that runs its body once for each item in a list or other collection, setting a loop variable to the current item.
- generator expression — A comprehension written in parentheses, which produces its items one at a time on demand instead of building a whole list.
- list — An ordered, changeable collection of values written in square brackets, such as [3, 1, 4].
- accumulation pattern — A loop pattern that builds a result step by step, starting from an initial value and combining each item into it, such as adding up a list.
Taught in
- Instability: Change Fail Rate And Deployment Rework Rate — DevOps & Site Reliability Engineering
- Restoration: Failed Deployment Recovery Time — DevOps & Site Reliability Engineering
- Appending To Lists, Sets, Constructors — Hands-on Python: Complete Video Course & Book
- Any Type As A Condition — Hands-on Python: Complete Video Course & Book
- Reading A Traceback Like A Professional — Hands-on Python: Complete Video Course & Book
- Comprehensions — Hands-on Python: Complete Video Course & Book
- Lists: Slices, Methods And Aliases — PCEP Certified Entry-Level Python Programmer (PCEP-30-02) Exam Prep
- Collections Sprint — PCEP Certified Entry-Level Python Programmer (PCEP-30-02) Exam Prep
- The Class That Shared One List — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Sixty Five Minutes, Forty Items: How PCAP Is Run — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Object-Oriented Sprint — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- List Comprehensions, Filtered And Nested — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Generators And Iterators — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Closures: Functions That Remember — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- read, readline, errno And bytearray — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Comprehensions, Closures And Files Sprint — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Twelve Traps, Mostly Objects — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep