Skip to content

Instantly share code, notes, and snippets.

@hchocobar
Last active May 18, 2025 14:40
Show Gist options
  • Save hchocobar/d12d31c4ccde8a5f6c318d3eb02f7789 to your computer and use it in GitHub Desktop.
Save hchocobar/d12d31c4ccde8a5f6c318d3eb02f7789 to your computer and use it in GitHub Desktop.
Python - List & Dict Comprehension (with Examples)

Python - list & dict comprehension

Example 1 - Create a list (flask example)

Implementation 1: standard

@app.route('/persons', methods=['GET'])
def get_persons():
    response_body = {}
    rows = db.session.execute(db.select('Persons')).scallars()
    # Create a list
    results = []
    for row in rows:
       results.append(row.serialize())
    response_body['results'] = results
    return response_body, 200

Implementation 2: list comprehension

@app.route('/persons', methods=['GET'])
def get_persons():
    response_body = {}
    rows = db.session.execute(db.select('Persons')).scallars()
    results = [row.serialize() for row in rows]  # Create a list with list comprehension
    response_body['results'] = results
    return response_body, 200

Implementation 3: lambda

@app.route('/persons', methods=['GET'])
def get_persons():
    response_body = {}
    rows = db.session.execute(db.select('Persons')).scallars()
    results = list(map(lambda row: row.serialize(), rows))  # Create a list with lambda
    response_body['results'] = results
    return response_body, 200

Example 2 - Create a dictionary

Implementation 1: standard

def check_frequency(a_list):
    frequency = {}
    for character in set(a_list):
       frequency[character] = a_list.count(character)
    return frequency


my_list = ['a', 'b', 'a', 'd', 'c', 'd', 'b', 'a', 'b']
check_frequency(my_list)  # Output: {'c': 1, 'd': 2, 'a': 3, 'b': 3}

Implementation 2: dict comprehension

def check_frequency(a_list):
    return {character: a_list.count(character) for character in set(a_list)}


my_list = ['a', 'b', 'a', 'd', 'c', 'd', 'b', 'a', 'b']
check_frequency(my_list)  # Output: {'c': 1, 'd': 2, 'a': 3, 'b': 3}

Example 3 - Create a matrix

Implementation 1: comprehension standard

def matrix_builder(n):
    row = [1 for i in range(0, n)]  # Crea una lista con 'n' 1s
    matrix = [row for i in range(0, n)]  # Crea una lista con 'n' columnas
    return matrix

Implementation 2: comprehension advanced

def matrix_builder(n):
    matrix = [[1 for i in range(0, n)] for i in range(0, n)]  # Crea una matriz de n x n
    return matrix

Implementation 3: comprehension advanced

def matrix_builder(n):
    return [[1 for i in range(n)] for i in range(n)]  # Omitimos el 1er parametro de range()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment