What are the differences between Python 2 and Python 3

Python 3 was first released in 2008 as a major revision of the language that aimed to correct flaws in the Python 2 language design.

While Python 2 development stopped in 2020, Python 3 is still actively developed and has become the standard version for new Python projects.

Here are some of the key differences between Python 2 and Python 3:

  • Print is a statement in Python 2 and a function in Python 3.
    The print() function was introduced in Python 3.
  • Python 3 uses Unicode string types by default instead of ASCII strings like in Python 2.
    This allows Python 3 to natively handle text encoding and work seamlessly with international characters.
  • Python 3 features new syntax like the f-string for string formatting. Python 2 uses the old % formatting syntax.
  • Python 3 embraces iterators and generators fully. Some Python 2 iterator patterns had to be encoded as workarounds but work naturally in Python 3.
  • Exception handling is smoother in Python 3 with the addition of the as keyword for extracting error messages cleanly.
  • Python 3 does away with old features like xrange() and .keys()/.values() returning lists instead of efficient iterators.
  • The new async/await keywords introduce native asynchronous programming in Python 3, avoiding callback hell.
  • Python 3 code runs faster overall than equivalent Python 2 code because of under-the-hood optimizations.
  • Python 3’s int type has unlimited size unlike Python 2’s int type.
  • Python 3 features cleaner module reorganization like new IO libraries and error handling in subdirectories.

The clear advantages Python 3 provides make it the ideal choice for new Python projects. Key changes allow for cleaner, more modern code. Python 3 also continues to receive improvements while Python 2 is end-of-life.

Migrating legacy Python 2 code to Python 3 is highly recommended.

Resources:

https://www.python.org/download/releases/2.0/

https://www.python.org/downloads/