Skip to content

Instantly share code, notes, and snippets.

@bjpcjp
Created January 19, 2025 17:47
Show Gist options
  • Save bjpcjp/181bc99ebeaae8078f1b3e34b5492402 to your computer and use it in GitHub Desktop.
Save bjpcjp/181bc99ebeaae8078f1b3e34b5492402 to your computer and use it in GitHub Desktop.
10 python one-liners (KD nuggets)
# https://www.kdnuggets.com/10-python-one-liners-change-coding-game
# 1. Lambda Functions
price_after_discount = lambda price: price*0.9
# 2. Map Operations on Lists
discounted_prices = list(map(price_after_discount, prices))
# 3. Unpacking Lists - print all these prices one by one
product_prices = [19.99, 5.49, 12.99]
print(*product_prices)
# 4. List Comprehension with a Condition
products = ["Keychain", "T-Shirt", "Mug", "Magnet", "Snow Globe"]
# build new list containing the indices of products whose name starts with 'M'.
[index for index in range(len(products)) if products[index][0] == 'M']
# 5. Checking Conditions Efficiently with any and all - both return a True/False value
inventory = [4, 0, 7, 10, 0]
any_out_of_stock = any(stock == 0 for stock in inventory)
all_in_stock = all(stock > 0 for stock in inventory)
# 6. combine assignment and variable initialization with a Walrus operator
if (n := len(customer_review)) < 10: print("Minimum 30 characters required")
# 7. Sorting Dictionary Entries by Values
sales_data = {
'Keychain': 1200,
'T-shirt': 800,
'Mug': 500,
'Magnet': 1500
}
sorted_sales = dict(sorted(sales_data.items(), key=lambda item: item[1], reverse=True))
# 8. Filter Entries with filter
best_selling_products = list(filter(lambda item: item[1] > 1000, sales_data.items()))
# 9. Use reduce to Perform Aggregations
total_sales = reduce(lambda x, y: x + y, sales_data.values())
# 10. Generate List Permutations
from itertools import permutations
list(permutations(['Alicia', 'Bob', 'Cristina', 'David']))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment