ricardomol
  • Ricardomol Notes
  • Frontend
    • Javascript Toolchain
    • Javascript
      • Quirks
      • Articles
        • Function caching
        • 12 JS Tricks
      • Closures
      • Assorted
      • ES6
      • this
      • OOP
      • Async Programming
      • Functional Programming
      • Typescript
    • React
      • Patterns
        • Render props
      • React Router
    • Webpack
    • CSS
      • Resources
  • Backend
    • Python
      • Shallow copy vs deep copy
      • Classes
      • Resources
      • Python C Extensions
      • Coroutines
      • Exceptions
      • Context managers
      • One-Liners
      • Open function
      • Object introspection
      • Targeting Python 2 + 3
      • For - else
      • Comprehensions
      • Lambdas
      • __slots__ magic
      • Collections
      • Enumerate
      • Mutation
      • Map, Filter and Reduce
      • Decorators
      • Sets
      • Fluent Python summary
      • Quizes / Tips
      • Generators
    • Django
      • Generic Relations
      • FBV's vs CBV's
      • ORM
      • DRF
    • RESTful Architecture
    • Resources
  • Databases
    • Joins
    • Normalization
    • PostgreSQL
  • DevOps
    • Docker
      • 0. Resources
      • 2. Services
      • 3. Swarms
      • 5. Stacks
      • 6. Deploy your app
    • CI
      • CI with Django
    • CD
    • PaaS
    • WSGI servers
    • Django
      • Django Deployment
    • Modern DevOps with Django
  • Git
    • Git
  • Comp Sci
    • Big O Notation
    • Patterns
    • Programming paradigms
  • Assorted
    • TCP vs UDP
    • Tests
    • MongoDB
    • Node
      • Resources
    • Go
    • HTTP vs HTTP2
    • GraphQL
    • Books
    • Vim
    • IPv4 vs IPv6
    • Regex
    • Redis
    • Celery
      • Brokers
    • Caching
  • SECURITY
    • Security
Powered by GitBook
On this page
  • Comprehensions
  • list comprehensions
  • dict comprehensions
  • set comprehensions
  • generator comprehensions
  1. Backend
  2. Python

Comprehensions

Comprehensions

Constructs that allow sequences to be built from other sequences.

Several types of comprehensions are supported:

  • list comprehensions

  • dictionary comprehensions

  • set comprehensions

  • generator comprehensions

list comprehensions

Short way to create lists.

Square brackets

Blueprint

variable = [out_exp for out_exp in input_list if out_exp == 2]

Example:

multiples = [i for i in range(30) if i % 3 == 0]
print(multiples)
# Output: [0, 3, 6, 9, 12, 15, 18, 21, 24, 27] 

Example with for loop:

squared = []
for x in range(10):
    squared.append(x**2)

Example with list comprehensions:

squared = [x**2 for x in range(10)]

dict comprehensions

Short way to create dicts

Curly braces {}

Example:

mcase = {'a': 10, 'b': 34, 'A': 7, 'Z': 3}

mcase_frequency = {
    k.lower(): mcase.get(k.lower(), 0) + mcase.get(k.upper(), 0)
    for k in mcase.keys()
}

# mcase_frequency == {'a': 17, 'z': 3, 'b': 34}

In the above example we are combining the values of keys which are same but in different typecase.

Example: switch keys and values of a dictionary:

{v: k for k, v in some_dict.items()}

set comprehensions

Short way to create sets

Curly braces {}.

Example:

squared = {x**2 for x in [1, 1, 2]}
print(squared)
# Output: {1, 4}

generator comprehensions

They don’t allocate memory for the whole list but generate one item at a time.

More memory efficient.

Example:

multiples_gen = (i for i in range(30) if i % 3 == 0)
print(multiples_gen)
# Output: <generator object <genexpr> at 0x7fdaa8e407d8>
for x in multiples_gen:
  print(x)
  # Outputs numbers
PreviousFor - elseNextLambdas

Last updated 6 years ago