Skip to content

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.

Using the else keyword to run when a for loop completes in Python

python
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

Using list comprehension with conditional operations in Python

python
squares = [i**2 if i % 2 == 0 else -(i**2) for i in range(10)]
print(squares)

<div class="alert alert-info flex not-prose"> Watch a course Python - The Practical Guide</div>

  1. *args and **kwargs : these are special keyword in function signature. They allow to pass variable number of arguments and keyword arguments respectively.

**Using *args and kwargs in Python to pass variable number of arguments and keyword arguments in Python

python
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.

Using the enumerate function to iterate over a list and keep track of the index in Python

python
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.

zip function in Python

python
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.

Ternary operators in Python

python
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.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.