Python: Hidden Features — part 3
Hi Everyone, In this article I will go throw couple of techniques or features which anyone can use in day to day coding.
In my journey through these Python features, I’ve uncovered techniques that go beyond the ordinary adding a touch of magic to our code.
Lets get started -
1. walrus operator (:=)
This was released in python 3.8 version. This helps us in defining value while using inside function.
Lets see an example -
def extract_val():
for i in range(10):
yield i
yield -1
def some_func(val):
pass
gen_obj = extract_val()
val = next(gen_obj)
while val != -1:
some_func(val)
val = next(gen_obj)
In this example I am creating a generaor object and then calling the next function to get the next value.
I am checking if the value is not negative 1, then I am calling some other function and then getting the next value.
Now lets see the same example with walrus -
def extract_val():
for i in range(10):
yield i
yield -1
def some_func(val):
pass
gen_obj = extract_val()
while (val := next(gen_obj))!= -1:
some_func(val)
Basically, here I am using the value as a result of my loop and at the same time I am using the result as the part of the condition in the while loop.
2. ** to unpack dictionary
Let’s see this with an example —
dict_data = {
1: "value1",
2: "value2",
}
def print_date(key, value):
print(key, value)
print(dict_data["1"], dict_data["2"])
I can unpack the `dict_data` by using above method that is dict_data of keys to pass to the function.
However I can pass the values by using the double astrix operator to unpack the values.
dict_data = {
1: "value1",
2: "value2",
}
def print_date(key, value):
print(key, value)
print_date(**dict_data)
And the interesting part is if I will change the order of the arguments in the print_data function — `def print_date(key, value)`, it still going to work.
3. divmod
divmod
can be used to format numbers in a more structured manner, such as displaying time in hours and minutes. So basically, it’s used to perform division and modulus operations in a single step.
total_minutes = 125
hours, minutes = divmod(total_minutes, 60)
print(f"{hours} hours and {minutes} minutes") # o/p - 2 hours and 5 minutes
4. extract nested list
Given a list, list lst = [[1], [2], [3], [4], [5]]
. In order to flatten it one can follow an old below approach
new_lst = []
for sublist in lst:
for element in sublist:
new_lst.append(element)
print(new_lst)
## OR using list compression
flattened_lst = [val for sublist in List1 for val in sublist]
print(flattened_lst)
But, there’s a technique which is often used to flatten a list of lists into a single list and that in return makes the code concise and readable.
for example —
List1 = [[1], [2], [3], [4], [5]]
flattened_lst = sum(lst, [])
print(flattened_lst)
# O/P = [1, 4, 2, 3, 4, 5]
sum(lst, [])
concatenates all sublists in lst
into a single list. The []
serves as the initial value for the sum operation, ensuring that the result is a list. So, Its good, but its not memory efficient though.
But, There’s another method as well using itertools.chain()
. This approach is memory-efficient as it avoids creating intermediate lists and is suitable for handling large datasets.
for example —
from itertools import chain
List1 = [[1], [2], [3], [4], [5]]
flattened_lst = list(chain.from_iterable(List1))
print(flattened_lst)
But, I will suggest to consider the specific requirements and characteristics of the data, as well as the desired balance between performance, readability, and ease of implementation.
5. union typing
Union types, introduced in Python 3.10, allow variables, function parameters, and return types to accept values of multiple types. This feature enhances code expressiveness and type safety, allowing developers to specify precisely which types are acceptable in a given context.
example —
from typing import Union
def process_data(data: Union[int, float, str]) -> None:
print(data)
process_data(10) # Valid
process_data(3.14) # Valid
process_data("hello") # Valid
Conclusion
Above are the few features or you can techniques which reinforce the importance of exploring beyond the basics and continuously learning in the ever-evolving Python ecosystem.
Happy coding !!