The world’s leading publication for data science, AI, and ML professionals.

Python But It’s Weird

Code snippets that will question your Python skills

Photo by Vinicius "amnx" Amano on Unsplash
Photo by Vinicius "amnx" Amano on Unsplash

We all love Python! After using this language for a long time, if you go deeper into concepts, you will be amazed by the modularity of this language. In my experience, I find it easy to implement most of my Data Analysis work using a combination of Python, a bit of PowerBI, and SQL on top of it.

But with these many features, there are some really weird Python concepts and codes that you might/might not have encountered on your programming journey. Maybe it was skipped, or you assumed it to be explicitly true for Python, with no explanation. Let me present some of these examples.

Do increment/decrement operators work in Python?

Photo by Volodymyr Hryshchenko on Unsplash
Photo by Volodymyr Hryshchenko on Unsplash

In Programming languages like C/C++/Java/Go, we have increment (++) and decrement operators (- -) that update the value of the variable by 1. These are commonly used while iterating in a loop.

If you try to use these operators in Python, here is what you will get:

>>> a = 10
>>> print(++a)
>>> 10
>>> print(--a)
>>> 10
>>> print(a++)
>>> SyntaxError: invalid syntax
>>> print(a--)
>>> SyntaxError: invalid syntax

The post-increment/decrement returns syntax error as this type of syntax is not defined in the Python grammar. But what about pre-increment/decrement operators? How do we get results for these operators even if they return conceptually wrong answers?

Actually, a double plus (++) is treated as +(+a), which is parsed back to (a) and that’s why it didn’t raise any error. Instead, it returned the original value of "a". The same explanation goes for (- -a).

Are you using the round() function correctly?

Photo by Varun Gaba on Unsplash
Photo by Varun Gaba on Unsplash

Try to evaluate the following without using Python IDE:

>>> print(round(12.5) - round(11.5))

Probably, you would have rounded the value 12.5 as 13, 11.5 as 12, and the final answer as 1. This answer is wrong in Python 3.x!

Python’s 3.x round function is implemented using the banker’s or convergent rounding, which is different for the edge case of 5. The usual rule for values greater than 5 rounded up and less than 5 rounded down remains the same. For the edge case of 5, it rounds the number to the nearest even number.

This means that 12.5 would be rounded to 12 only as it is the nearest even number and 11.5 would also be rounded to 12, resulting in 0 as the final answer. So, use the round function with this case in mind!

Walrus operator behavior

Photo by Jay Ruzesky on Unsplash
Photo by Jay Ruzesky on Unsplash

With the release of Python 3.8, a new operator came into the limelight, walrus operator. As per the official docs, it is a type of assignment expression to be used in loops, expressions, and many more instances. It allows you to assign and return a value in the same expression.

All the possible instances are discussed in the official release and you can find it on PEP 572. One of the interesting use cases I found online is discussed below, where I take input for numbers until the input is -1.

In the general case, the code would look like this:

But, using walrus operator, it will be reduced to:

If you try to use the walrus operator as an assignment operator in the program, you will get a syntax error:

>>> a := func(x)
>>> SyntaxError: invalid syntax

It is because the walrus "unparenthesized assignment expression" is restricted to the top level. One can still use the walrus operator assignment by wrapping the expression in parentheses. This will be a valid expression, but not recommended.

>>> (a := func(45))

Circular reference

Photo by Matt Seymour on Unsplash
Photo by Matt Seymour on Unsplash

This concept really blew my mind, and I didn’t know if such a thing exists in Python language!

Suppose you declared a list as:

>>> some_list = some_list[0] = [0, 1]
  1. Here, a triple assignment has been done. In such cases, the extreme left and the extreme right are taken first and then the remaining assignment. Therefore, the some_list variable holds the value [0,1].
  2. Now the interesting part, the some_list[0] is to be assigned to [0,1]. You might think that it should throw an error but as the some_list variable has been assigned, it will not raise any error.
  3. But, we also know that [0,1] is assigned as some_list in the first place.
  4. It means that some_list[0] wants to refer to itself only. Even if the self-value is assigned, it will again refer to itself.
  5. This creates infinite referencing and is called circular referencing.
  6. Python handles this by assigning this infinite referencing value as ellipsis (…). Yes! if you print out the some_list variable, you will see this value.
>>> [[...], 1]

Even if you try to print some_list[0] in our case, you will get the same value as shown above. It will remain the same value for any number of levels! You can try another complex example that is quite famous:

>>> a, b = a[b] = {}, 5
>>> print(a)

Here also, initially, a and b are assigned the respective values as {} and b. For a[b], it assigns the b value 5 as the key for the dictionary but the value points to the dictionary a which is being updated. Therefore, key 5 would hold a tuple of ellipsis and the value 5.

{5: ({...}, 5)}

Conclusion

There are a lot of things to look upon in Python. Some of these are designed to happen in the manner defined and others are just the easter eggs discovered by the community. Things like string interning, GIL limitations, dictionary keys hashing based on equivalence, "is" operator usage, and the list goes on! You can check out the whole list by visiting this GitHub Repository which is a major source of all the things discussed in this article.

I hope you liked this article and if you did, make sure to show your support. In case of any doubts, queries, or potential opportunities, you can reach out to me via LinkedIn, Twitter, or GitHub.

Trending Articles –

  • 100k Views Club

Building Android Apps With Python: Part -1

  • 50K Views Club

3 Ways to Convert Python App into APK

Run Python Code on Websites: Exploring Brython

References –

  1. https://github.com/satwikkansal/wtfpython
  2. https://www.python.org/dev/peps/pep-0572/

Related Articles