How to Apply a Function to NumPy Elements

Problem Formulation and Solution Overview As a Pythonista, coding issues may occur where you need to apply a function against NumPy elements. To make it more fun, we have the following running scenario: We have a NumPy array containing five (5) negative numbers related to an inconsistent inventory count. Therefore, the Vice-President of Rivers Clothing … Read more

How to Apply a Function to List Elements

Problem Formulation and Solution Overview As a Pythonista, coding issues may occur where you need to apply a function against array/matrix elements. To make it more fun, we have the following running scenario: The organization Happy Mortgages has six (6) different Mortgage Terms available: 30-Year, 20-Year, 15-Year, 10-Year, 7-Year, and 5-Year terms. The US Federal … Read more

How To Apply A Function To Each Element Of A Dictionary?

This article shows you how to apply a given function to each element of a Python dictionary. The most Pythonic way to apply a function to each element of a Python dict is combining the dictionary comprehension feature and the dict.items() method like so: {k:f(v) for k,v in dict.items()} Note: All the solutions provided below … Read more

Python __format__() Magic Method

Syntax object.__format__(self, spec) The Python __format__() method implements the built-in format() function as well as the string.format() method. So, when you call format(x, spec) or string.format(spec), Python attempts to call x.__format__(spec). The return value is a string. We call this a “Dunder Method” for “Double Underscore Method” (also called “magic method”). To get a list … Read more

Python __set_name__() Magic Method

Python’s magic method obj.__set_name__(self, owner, name) method is created on an attribute obj when the class owner holding the attribute is created. We call this a “Dunder Method” for “Double Underscore Method” (also called “magic method”). To get a list of all dunder methods with explanation, check out our dunder cheat sheet article on this … Read more