blog
blog
blog
blog
blog

The Hidden Features Of Python

Python is one of the easy and expressive programming languages. Easy to understand and easy to explore, that's what Python is all about. But, there are some less known Python features that you might not know about. So let’s dive into the "Hidden Features of Python"

Blog

The term hidden is loosely used to indicate features which are generally unique to Python, or not very well known. Below are some Python features that you might not know,

1) Conditional Assignment

As a beginner, you might be familiar with Python conditionals that are, if, if-else, and more. Also, you might have worked with the smart “if-else” called a ternary operator. That said, what is the conditional assignment? Check this out,

x = 3 if (y == 1) else 2

It does exactly what it looks like. It means "Assign 3 to x if y is 1 else assign 2 to x". Isn’t that quick and easy rather than writing an if-else block?

2) The For...else

For...else is an effective way if using conditionals with the for loop. Mostly we use For loops to iterate over the sequence and fetch an element. So, to check whether that element exists or not, we generally use a boolean flag. Check the below example,

element = False
for i in list1:
if i == 5:
element = True
break
if not found:
print("i was never 5")


Now check the above same code using the for...else,

for i in list1:
if i == 5:
break
else:
print("i was never 5")


The else statement is executed if the loop has been completed without ever invoking break. That's super easy, right?

3) String Formatting

Many times you would have wanted to format strings according to your requirements, and using concatenation sometimes makes the code ugly. Here’s where String formatting comes in, Check this out,

print("My name is {foo} and my age is {bar}".format(foo='John’, bar=34))

The readability of this is definitely higher than making a large string by concatenating smaller strings with variables.

4) Handling Missing keys of a Dictionary

What if the key to access the dictionary is missing? Boom! Error… If a subclass of dict defines a method __missing__() and the key is not present, the d[key] operation calls that method with the key as an argument. The d[key] operation then returns or raises whatever is returned or raised by the __missing__(key) call. No other operations or methods invoke __missing__(). If __missing__() is not defined, KeyError is raised. __missing__() must be a method; it cannot be an instance variable. Check this,

class Counter(dict):
def __missing__(self, key):
return 0
c = Counter()
c[1]
Output:
0


5) Argument Unpacking

List unpacking fails when used on a function; Python doesn’t natively unpack a list or a tuple when it is passed to a function. This is because it may cause ambiguity: it’s up to the developer to specify when this has to be done. Example,

def function(x,y,z):
...
t = [1, 2, 3]
function(t[0], t[1], [2])


is equivalent to the,

function(*t)

The magic is done by the star operator. Python also has the double star operator, which is used to semantically unpack dictionaries:

def function(x,y,z):
print x,y,z
d = {'z':30, 'y':20, 'x':10 }
function(**d)


In this case, Python will match the keys of the dictionary with the name of the arguments in the function. In order for this to work, the keys in the dictionary must match the name of the arguments.

Hope you enjoyed exploring the hidden features of Python! Want to learn more about Python? Try our app, Programming Hero, and learn Python the fun way.

Related Post

related post

If you spend 3–4 hours daily for 7 days, you will become a Junior Python Developer. I am providing this guideline using this android app called: Programming Hero.

related post

I am taking all the examples from the Python learning app called Programming Hero: Coding Just Got Fun