Skip to content

Instantly share code, notes, and snippets.

@hchocobar
Last active August 4, 2023 18:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • 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 dictionary

Implementation 1: standard

def check_frequency_1(x):
    frequency = {}
    for c in set(x):
       frequency[c] = x.count(c)
    return frequency


numbers = ['a', 'b', 'a', 'd', 'c', 'd', 'b', 'a', 'b']
print(check_frequency_1(numbers))  # Output: {'c': 1, 'd': 2, 'a': 3, 'b': 3}

Implementation 2: comprehension

def check_frequency_2(x):
    return {c: x.count(c) for c in set(x)}


numbers = ['a', 'b', 'a', 'd', 'c', 'd', 'b', 'a', 'b']
print(check_frequency_1(numbers))  # Output: {'c': 1, 'd': 2, 'a': 3, 'b': 3}

Example 2 - Create a list (flask example)

Implementation 1: standard

@app.route('/person', methods=['GET'])
def get_perosn():
    persons = Person.query.all()
    # create a list
    results = []
    for person in persons:
       results.append(person.serialize())
    return jsonify(results), 200

Implementation 2: comprehension

@app.route('/person', methods=['GET'])
def get_perosn():
    persons = Person.query.all()
    # create a list
    results = [person.serialize() for person in persons]
    return jsonify(results), 200

Implementation 3: lambda

@app.route('/person', methods=['GET'])
def get_perosn():
    persons = Person.query.all()
    # create a list
    results = list(map(lambda person: person.serialize(),  persons))
    return jsonify(results), 200

Example 3 - Create a matrix

Implementation 1: comprehension standard

def matrix_builder_1(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 1

def matrix_builder_2(n):
    matrix = [[1 for i in range(0, n)] 
              for i in range(0, n)]
    return matrix

Implementation 3: comprehension advanced 2

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