Supprimer Rendre public Rendre privé Add tags Delete tags
  Ajouter un tag   Annuler
  Supprimer le tag   Annuler
  • • DevOps notes •
  •  
  • AI
  • Tags
  • Connexion

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)
3 months ago Permalien
cluster icon
  • If / Elif / Else Logic : If / Elif / Else Logic Control the flow of scripts based on conditions using if, elif, and else. The if Statement An if statement executes a block of ...
  • Handling Authentication : Handling Authentication APIs often require authentication to control access, rate limits, and auditing. Without authentication, requests to protected...
  • Adding Tests to a Multi-File Project : Adding Tests to a Multi-File Project Standard Project Layout with Tests To maintain a clean and organized codebase, it is standard practice to separat...
  • Range, zip : Efficient Looping: range Creating large lists for loops is memory-intensive (e.g., list(range(1_000_000))). range() stores only start, stop, and step...
  • Structured Logging : Introduction to Structured Logging Plain-text logs are hard to parse and brittle to format changes. Structured logging records events as key-value da...


(110)
Filtrer par liens sans tag
Replier Replier tout Déplier Déplier tout Êtes-vous sûr de vouloir supprimer ce lien ? Êtes-vous sûr de vouloir supprimer ce tag ? Le gestionnaire de marque-pages personnel, minimaliste, et sans base de données par la communauté Shaarli