Delete Set public Set private Add tags Delete tags
  Add tag   Cancel
  Delete tag   Cancel
  • • DevOps notes •
  •  
  • AI
  • Tags
  • Login

Concise Iteration: List Comprehensions/shaare/dAsQzQ

  • python
  • python

Concise Iteration: List Comprehensions

Simple for loops to create lists can be verbose. We can leverage list comprehensions to define the list contents directly within square brackets, obtaining a more compact syntax.

# Example: Double items using a for loop
old_items = [1, 2, 3, 4]
doubled_items = []

for item in old_items:
    doubled_items.append(item * 2)

print(doubled_items)

# Example: Double items using list comprehension
doubled_items_with_comprehension = [item * 2 for item in old_items]
print(doubled_items_with_comprehension)

List Comprehension Syntax

  • Syntax: [<expression> for <item> in <iterable>]
  • [] indicates a new list is created eagerly.
  • <expression> is applied to each item.
  • for <item> in <iterable> defines the loop.
servers = ["web", "db", "backend"]
uppercase_servers = [server.upper() for server in servers]
print(uppercase_servers)

Filtering with if in Comprehensions

  • Purpose: Include only items meeting a condition.
  • Syntax: [<expression> for <item> in <iterable> if <condition>].
  • The condition filters items before expression is evaluated.
numbers = [1, 5, 10, 8, 2, 15]
even_numbers = [num + 1 for num in numbers if num % 2 == 0]
print(even_numbers)

Set and Dictionary Comprehensions

  • Set comprehension uses {} and produces unique items.
  • Dictionary comprehension uses {key: value ...}.
  • Both evaluated eagerly like list comprehensions.
numbers = [1, 2, 3, 2, 4, 1, 3]
unique_squares = {x * x for x in numbers}
print(unique_squares)

servers = ["web", "backend"]
server_ips = {server: f"192.168.1.{i}" for i, server in enumerate(servers)}
print(server_ips)

Conditional Expression (Ternary Operator)

  • Purpose: Apply different expressions based on a condition within the comprehension.
  • Syntax: <value_if_true> if <condition> else <value_if_false> inside the comprehension.
  • Places the ternary before the for clause.
numbers = [1, 5, 10, 8, 2, 15]
categories = ["PASS" if num >= 8 else "FAIL" for num in numbers]
print(categories)
2 months ago Permalink
cluster icon
  • Variables, comments : Variables: Naming Values Naming Guidelines: Must start with a letter or underscore (_) and can contain letters, numbers, and underscores. Use snake_...
  • Exceptions : Common Built‑in Exceptions Python ships with a rich hierarchy of exception classes; most automation errors fall into a small, predictable subset. A...
  • Python Functions Are First‑Class Citizens : Python Functions Are First‑Class Citizens In Python, functions behave like any other object (strings, ints, lists). Because they are "first‑clas...
  • Regex : Regex Essentials: Overview Regular expressions (regex) are a language for defining text search patterns. Python’s re module provides functions like...
  • Logging to Files : Logging to Files Basic File Logging with FileHandler Use logging.FileHandler to write log records to a file. mode='a' (append) preserves existing log...


(97)
Filter untagged links
Fold Fold all Expand Expand all Are you sure you want to delete this link? Are you sure you want to delete this tag? The personal, minimalist, super-fast, database free, bookmarking service by the Shaarli community