Python Gotchas

python Jun 14, 2017

gotcha: n.
A misfeature of a system, especially a programming language or environment, that tends to breed bugs or mistakes because it is both enticingly easy to invoke and completely unexpected and/or unreasonable in its outcome.
For example, a classic gotcha in C is the fact that if (a=b) {code;} is syntactically valid and sometimes even correct. It puts the value of b into a and then executes code if a is non-zero. What the programmer probably meant was if (a==b) {code;}, which executes code if a and b are equal.

Here are some interesting python gotchas -

>>> value_or_values = 1, 
>>> # creates a tuple (1,)

>>> value_or_values[False]
>>> 1
>>> # returns value 1

>>> value_or_values[True]
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
>>> # See what happened there?

>>> isinstance(True, int)
>>> True
>>> # I am sure you must have figured it out now.

>>> # Very bad example of getting a list of even numbers but still ...
>>> # It gets us the desired result here, but never remove elements from a running list.
>>> li = range(10)
>>> for value in li:
>>> ...:     if value % 2 != 0:
>>> ...:      li.remove(value)
>>> ...:
>>> print(li)
>>> [0, 2, 4, 6, 8]

>>> # more soon

References :

Definition: Gotcha

Tags

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.