Skip to content

Instantly share code, notes, and snippets.

@pkutaj
Created April 22, 2022 07:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pkutaj/defa5b39badbf04a2e94d23a6df06727 to your computer and use it in GitHub Desktop.
Save pkutaj/defa5b39badbf04a2e94d23a6df06727 to your computer and use it in GitHub Desktop.
70.01-List-and-Set-Comprehensions.md

usecase

The aim of this page📝is to introduce comprehensions and their use for lists. Comprehensions are

  • syntactic sugar
    • readable
    • expressive
    • self-documenting by being close to natural language
  • or concise syntax for the description of:
    1. lists
    2. sets
    3. dicts

1. list comprehensions: syntax

  • it seems to be declarative like SQL is declarative
  • the expressino can be any python expression
  • usually the produce a items in a new list - this makes it similar to map (there you modify the existing values)
#[expression(item) for item in iterable]
list = ['pavol', 'ignatius', 'benedictus']
lengths = [len(name) for name in list] 
  • this is the synonym for the following imperative code
lengths = []
for name in list:
    lengths.append(len(name))

2. set comprehensions

  • same syntax, only in curly braces - the example is just an illustrative deduplication of the length of the first 19 integers
from math import factorial
s = {len(str(factorial(x))) for x in range(20)}
type(s)
<class 'set'>
print(s)
{1,2,3,4,5,6,7,8,9,10,11,13,14,15,16,18}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment