Did you ever do something that your friends saw and said "Wow, how did you know that?"
Well, this blog aims to help you discovering (or getting a better understanding) of techniques that can level up your code notably if you did not know them before.
Some of this techniques are python-specific, while the others are present in other languages but are considered pythonic (nice practices in python code).
After reading this blog you may be able to flex a bit on your fellow beginner developers 😉.
What will you learn❓
- String formatting and interpolation ✔️
- Inline conditionals ✔️
- List comprehensions ✔️
- Lambda functions ✔️
- Type hinting ✔️
⛓️ String formatting and interpolation
The first way that people often learn to join values and strings is the concatenating method:
words = "5"
concat_str = "This string has " + words + " words"
However, this method is not very readable and doesn't work on many languages.
Interpolated strings are a way of combinating variables and fixed strings in a more visual way, which can help code insight and debugging.
Also, it offers more configuration capabilities in the way we want to represent the values.
The way that string interpolation works is by inserting other values as strings or objects into the original string.
The next three ways are much better and have some useful particularities:
- f-strings (my favourite)
- .format()
- % operator
f-strings
On python version 3.6 and higher, a new way of interpolating strings was added, which is the f-string.
The way it is used is by adding the prefix "f" or "F" before the string.
words = 5
concat_str = f"This string has {words} words"
Notice how the interpolated values don't have to be of type str
This method offers some configuration capabilities, I.E: defining the number of decimals to show on a float.
num1 = 3.141592
num2 = 6.6743
concat_str = f"2 decimals: {num1:.2f} and 4 decimals: {num2:.4f}
print(concat_str)
-> Output: "2 decimals: 3.14 and 4 decimals: 6.6743"
.format()
The .format() method is another way of interpolating strings, but it comes with a big particularity: it uses lazy evaluation
The concepts of eager and lazy evaluations both deserve a dedicated blog, so if you want to see a blog about them, let me know 😉.
The way to use it is as follows:
day = "saturday"
month = "may"
concat_str = "current day and month: {day},{month}".format(day=day,month=month)
print(concat_str)
-> Output: "current day and month: saturday, may"
Modulo (%) operator
A more "primitive" interpolation method that also appears when formatting strings in C.
It is used by placing the % icon in the place we want the value printed, next to its type and other flags as the number of decimals to show.
day = "saturday"
hour = 12.06
concat_str = "day: %s, hour: %.2f" % (day, hour)
print(concat_str)
-> Output: "day: saturday, hour: 12.06"
✅-❎ Inline conditionals
Inline conditionals are a cool way of condensing expressions in less lines and eliminate a bit of the verbosity of traditional if statements.
This is the general syntax for inline conditionals:
expression_if_true if condition else expression_if_false
Here is an example of inline conditionals in python:
value = True
print("value is True") if value else print("value is False")
-> Output: "value is True"
Another example manipulating the value of a variable:
value = False
num = 1 if value else 0
print(num)
-> Output: 0
[🧾] List comprehensions
One of my favourite python techniques, widely used in data science where big sets of information are used and manipulated.
List comprehensions are a way of writing a list (or other data collection types) out of another iterable variable in a single line.
Imagine we have a list of fruits named fruits
fruits = ["apple", "banana", "pear", "peach"]
and we want to create another list consisting of fruits that have a p in their name, the list comprehension used would be like this one:
fruits_with_p = [fruit for fruit in fruits if "p" in fruit]
The meaning of the line of code from above is "Each element will be a fruit element of the list fruits if there's a "p" in said element fruit"
List comprehensions often demand some knowledge of how to create inline conditionals, as you may have seen.
Also, an important thing to note is that list comprehensions are generally faster than their equivalent in a for loop expression. This is mainly because list comprehensions move better the computation to C rather that using the python computation.
(kudos to u/toastedstapler - https://www.reddit.com/r/learnpython/comments/i28kcn/why_are_list_comprehensions_so_much_faster_than/
❗HOWEVER list comprehensions are known for difficulting the readability of the code when used without conscience, so don't abuse of their power.
λ Lambda functions
Lambda functions (also called anonymous functions) are basically definitions of functions that are short, concise and usually not worth to declare as a traditional function.
They could be imagined as some kind of inline function declarations.
Their syntax is
lambda arguments : expression
Even though lambda functions can be declared inline and called when needed as in the following example, this is not their main use.
day_and_month = lambda day, month : print(f'day: {day}, month: {month}')
day_and_month("saturday", "may")
-> Output: "day: saturday, month: may"
Usually lambda functions are used as parameters to generator functions like map() and are often used in Data Science.
The following is an example of using a lambda function as a parameter
celsius_temps = [0, 20, 25, 30, 37]
fahrenheit_temps = list(map(lambda c: (c * 9/5) + 32, celsius_temps))
print(fahrenheit_temps)
-> Output: [32.0, 68.0, 77.0, 86.0, 98.6]
The above code takes an anonymous function that converts celsius degrees to fahrenheit and applies it to each element in the celsius_temp list.
Lambda functions can usually be replaced by list comprehensions, with the following code in this case:
celsius_temps = [0, 20, 25, 30, 37]
fahrenheit_temps = [c * 9/5 + 32 for c in celsius_temps]
print(fahrenheit_temps)
-> Output: [32.0, 68.0, 77.0, 86.0, 98.6]
So the usage of each implementation depends on the programmer and the specific needs in the moment.
💡 Type hintings
Type hintings are a useful way to make your code much more readable and easy to debug.
Python is a dynamically typed language, which means that the variables don't have a specific data type in the moment of their creation.
Type hintings can help the IDE or linting software to interpret the code and give better insights in case of errors or warnings.
Variables can be type-hinted as they are created and also in the expected parameters of a function.
Example of type hinting at creation of variables:
a:int = 5
b:float = 3.5
s:str = "string"
l:list = [a, b, s]
Example of type hinting at definition of a function:
# Function that searches a word in a list and returns its index
def search_in_list(original_list:list, word:str) -> int:
for i,elem in enumerate(original_list):
if elem == word:
return i
return -1
Using this technique, the readability and facility to debug your code will updgrade a lot.
Hope you found this knowledge useful! If you have anything to contribute, feel free to comment it!
Also, if you are interested in ML, computer vision or fitness in general, I suggest to check my devlog series about my latest side-project, FitVision 👀 https://dev.to/ceir/fitvision-devlog-1-3a0i