W3docs

Hidden features of Python

There are many hidden features of Python, some of which are not well-known even among experienced Python programmers.

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— editable, runs on the server
  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— editable, runs on the server

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> 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

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— editable, runs on the server
  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— editable, runs on the server
  1. Ternary Operator : python provide an shorthand to do the if-else block.

Ternary operators in Python

python— editable, runs on the server

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.