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:

  1. The else clause in a for loop: In a for loop, the else clause is executed when the loop completes normally (i.e., not when the loop is terminated by a break statement). This can be used to perform some operation after the loop, but only if the loop completed without interruption.
for i in range(10):
    if i == 5:
        break
else:
    print("The loop completed normally")
  1. List Comprehensions with if-else : This allow to have if-else block in the list comprehension
squares = [i**2 if i % 2 == 0 else -(i**2) for i in range(10)]
print(squares)

Watch a course Python - The Practical Guide

  1. *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)
  1. 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)
  1. 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)
  1. Ternary Operator : python provide an shorthand to do the if-else block.
x,y = 5,10
smaller = x if x < y else y
print(smaller)

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.