How-to articles, tricks, and solutions about PYTHON

Why do Python classes inherit object?

In Python 3, all classes automatically inherit from the object class.

Why does code like `str = str(...)` cause a TypeError, but only the second time?

Code like str = str(...) causes a TypeError because it attempts to re-assign the built-in str type to a new value, which is not allowed.

Why does comparing strings using either '==' or 'is' sometimes produce a different result?

When comparing strings using the '==' operator, the comparison is based on the actual characters in the string.

Why does Python code run faster in a function?

Python code can run faster in a function because of something called "Just-In-Time" (JIT) compilation.

Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?

The range() function generates a sequence of numbers, starting from the first argument, and ending before the second argument.

Why is it string.join(list) instead of list.join(string)?

The join() method is a string method, so it is called on a string object and takes a list of strings as its argument.

Why is python setup.py saying invalid command 'bdist_wheel' on Travis CI?

The error message "invalid command 'bdist_wheel'" occurs when the "bdist_wheel" module is not installed.

Why use pip over easy_install?

Pip is generally preferred over easy_install because it offers a number of features that easy_install does not, including better package management and more user-friendly command options.

Working with UTF-8 encoding in Python source

Here is a code snippet that demonstrates how to work with UTF-8 encoding in a Python source file:

Writing a list to a file with Python, with newlines

Here is a code snippet that demonstrates how to write a list to a file with newlines in Python:

Writing a pandas DataFrame to CSV file

In the above code snippet, the to_csv method is used to write a DataFrame to a CSV file.

Writing string to a file on a new line every time

Here is an example code snippet for writing a string to a file on a new line every time in Python: