Hidden features of Python
There are many hidden features of Python, some of which are not well-known even among experienced Python programmers. Here are a few examples:
- The
else
clause in afor
loop: In afor
loop, theelse
clause is executed when the loop completes normally (i.e., not when the loop is terminated by abreak
statement). This can be used to perform some operation after the loop, but only if the loop completed without interruption.
- List Comprehensions with
if-else
: This allow to have if-else block in the list comprehension
Watch a video course
Python - The Practical Guide
*args
and**kwargs
: these are special keyword in function signature. They allow to pass variable number of arguments and keyword arguments respectively.
def my_function(*args, **kwargs):
print(args)
print(kwargs)
- The
enumerate()
function : This function allows you to iterate over a list and also keep track of the index of the current element.
my_list = ['firstValue', 'secondValue', 'thirdValue']
for i, value in enumerate(my_list):
print(i, value)
zip()
function: This function allows you to combine multiple lists into a single list of tuples, where the i-th tuple contains the i-th element from each of the input lists.
a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
zipped = zip(a, b, c)
# Returns an iterator of tuples, where the first tuple contains the first element of each input list
print(zipped)
- Ternary Operator : python provide an shorthand to do the if-else block.
These are just a few examples of the many hidden features that Python has to offer. Learning about these features can make your code more efficient, readable, and elegant.