François Constant logo

Nice Python shortcuts

October 2023

Just 4 shortcuts for now - latest update in October 2023.

1. Filter a list and extract values in a one-liner

Before

def get_cheap_products_names(products):
    cheap_products = []
    for product in products:
        if product.price < 20:
            cheap_products.append(product.name)
    return cheap_products

After

def get_cheap_products_names(products):
    return [product.name for product in products if product.price < 20]

2. Update and return a dictionary in a one-liner

Before

class B(A):
    def get_context(self):
        context = super().get_context()
        context["something_good"] = "Fruit"
        return context

After

class B(A):
    def get_context(self):
        return { **super().get_context(), "something_good": "Fruit" }

3. Conditional assignment in a one-liner

Before

brand = "Toyota"

if money:
    brand = "Lexus"

After

brand = "Lexus" if money else "Toyota"

4. Unpack tuples in a for-loop directly

Before

for folk in [("Bob", 76), ("Alice", 75)]:
    name = folk[0]
    age = folk[1]
    print(f"Name: {name}")
    print(f"Age: {age}\n")

After

for name, age in [("Bob", 76), ("Alice", 75)]:
    print(f"Name: {name}")
    print(f"Age: {age}\n")