Difference Between Python 2 and 3

Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Learn via video course

Python Certification Course: Master the essentials
Python Certification Course: Master the essentials
By Rahul Janghu
Free
star4.90
Enrolled: 1000
Python Certification Course: Master the essentials
Python Certification Course: Master the essentials
Rahul Janghu
Free
4.90
icon_usercirclecheck-01Enrolled: 1000
Start Learning

Introduction to Python 2.x and Python 3.x

Python 2.x and Python 3.x are two of the most used python versions in real-world application development.They both come with a lot of features and library support. Although Python 2.x official support is discontinued in 2020, 2.x language is still used extensively for existing tools development/fixes and also because many developers are migrating their code from 2.x to 3.x which requires the knowledge of Python 2.x. This article explores the major differences between python 2.x and 3.x, starting with a brief introduction to each version.

What is Python 2?

Python 2.x or Python 2 is a python programming version that has been released with several new feature updates and fixes to the earlier python versions of 0.x and 1.x. The first version in python 2.x is Python 2.0 which was released on 16 October 2000. The latest version is Python 2.7, and it was discontinued from the year 2020 and there will be no more releases in Python 2.x.

History of Python 2

Below is a brief history of the important feature updates seen in python 2.x versions -

  • Python 2.0, released in October 2000 introduced list comprehensions and garbage collectors.
  • Python 2.1, released in April 2001 supports nested scopes like other static scoped languages.
  • Python 2.5 was released in September 2006, which introduced the with statement.
  • Python 2.7, released in July 2010 is the last release in the 2.x series of python. Python 2.7 official support ended on January 1, 2020. A final release 2.7.18, occurred on April 20, 2020, which included fixes for critical bugs and release blockers. This marks the end-of-life of Python 2

For Example, here is the doc link for Python 2.0:

Example Code of Python 2

Output:

Above is an example of the hello world python 2 code. The above program will throw a syntax error when executed in python 3, because the print is changed from a statement in Python 2 to a function in python 3 and the syntax is also modified. We shall explore this difference in detail in the ‘Difference between python 2 and 3’ section of this article.

Why should you learn python 2?

  • Below are some of the reasons why you probably still need to learn/work in python2 even though the latest version Python 3 is released
  • Issues present in python 2.x like Integer division, List comprehension, etc are resolved in Python 3.x with modifications in syntax and usage. We shall discuss more on these issues with examples in the ‘Difference between python 2 and 3’ section of this article
  • Since it is advised to migrate existing python 2.x code to python 3.x, knowledge of python 2.x is needed to work with any existing codebases
  • If you with your team are working on a project that depends on specific third-party libraries or software which you are not able to port/use in Python 3, then Python 2 is an option available for you since it has been around the 2000s and has many support libraries and frameworks
  • For a DevOps Engineer, you’d be required to work on configurations management tools like puppet or ansible Here, you may need to work with both versions of python
  • So finally, even though python 2 has reached the end of life in 2020 with no official support any longer, it still has rich library support, and also some of the Linux and macOS distributions still use 2.x as default.

What is python 3?

Python 3.x or Python 3 is an updated version of python programming that has been released mainly to fix the fundamental design problems that exist in Python 2. The changes required to fix the flaws could not be implemented while retaining full backward compatibility with the 2.x series, which necessitated a new major version number which is 3.x.

The first version in python 3.x is Python 3.0 which was released in 2008. The latest stable version is Python 3.9 which was released in 2020. The nature of python 3 is that the changes made in python 3 make it incompatible with python 2. So it is backward incompatible and code written in python 3 will not work on python 2 without modifications.

History of Python 3

Below is a brief history of the important feature updates seen in Python 3.x -

  • Python 3.0 also known as “Python 3000” or “Py3K”, which was released on December 3, 2008, was the first-ever intentionally backward-incompatible Python release. It introduced many changes in the fundamental design which posed an issue in python 2.5 and python 2.6 at that time. We shall discuss the difference and the changes introduced in detail in the Difference between Python 2 and 3 section of the article.
  • Python 3.2 was released in 2011 introduced argparse command-line parsing module to overcome limitations present in optparse. It also added concurrent module which contains code for creating and managing concurrency.
  • Python 3.9, which is the latest stable release that came out in 2020, gave out several improvements in the interpreter, newly added string methods, union operators in dictionaries, and few new libraries as well.

For Example, here is the doc link for python 3.0 :

Example Code of Python 3

Output:

Above is an example, hello world python 3 code. The above program will throw a syntax error when executed in python 2. Because print is one of the syntax changes between Python 2 and Python3. We shall look into the changes between Python 2 and 3 in detail in the Difference between Python 2 and 3 section of the article.

Why should you learn python 3?

Below are some of the reasons why you should learn/work in python 3:

  • It is easy getting help/support as Python 3 is currently officially supported with a large Python developer's community.
  • It offers many toolkits and libraries and also supports many modern techniques like AI, Machine learning, and Data Science.
  • It is easier to learn and pick up for any budding programmer who is looking for a language that is rich in library resources.
  • It also supports integration with many other programming languages.

Difference Between Python 2 and 3

Below are the key differences that are between Python 2.x and 3.x:

1. Print Function

In python 2 print is a statement so it is written as print <output content>. But in python 3 it is a function, so it is written as print(<output content>) with the parentheses and the output inside the parentheses.

The below examples make the usage difference of print in python 2.x and 3.x clear.

Python 2.x print statement usage:

Output:

Now let us take a look at the same print statement in python 3.x, notice the difference:

Python 3.x print statement usage:

Output:

Note: Print statement with parentheses i.e., print() will work in python 2.x because here it is evaluated as a print statement followed by an (<expression>) in parentheses. So, print(<expression>) is valid in python 2.x. But the opposite is not true i.e, writing print without parentheses in python 3.x will throw a syntax error because print is a function in python 3.x so the parentheses are required to execute.

2. Integer Division

In python 2.x, all the numbers given without decimal points are treated as integers, so sometimes the division of two integers in python 2.x might lead to unexpected results. For example, if you try to execute 5/4 in python 2, the result will be 1 instead of 1.25. This is because here both 5 and 4 are treated as integers and so the result will not contain any decimal points. This behavior is fixed in python 3. Take a look at the below statements in python 2 and 3 and their outputs to understand this better.

Python 2.x division operator:

Output:

Python 3.x division operator:

Output:

Note: During porting of code from python 2.x to 3.x or vice versa, one needs to be careful while evaluating the integer divisions as they may go unnoticed, because they won’t throw any errors during compilation but give unexpected outputs later.

3. Unicode Strings

By default, python 2 stores strings as ASCII and require you to mark the string specifically with a “u” if you wish to store them as Unicode. Whereas, python 3 stores strings as Unicode by default. Unicode strings are more versatile compared to ASCII strings as they can store letters from foreign languages as well as emojis and the standard Roman letters and numerals

Python 2.x Unicode Strings:

Output:

Python 3.x Unicode Strings:

Output:

4. Error Handling

In the except clause of try-except block, ‘as’ keyword is added in python 3.x, which was not there previously in python 2. Moreover, the ‘as’ keyword is made mandatory in python 3. If not specified in python 3 it throws an error. Take a look at the below sample code of python 2.x and 3.x to understand it better.

Python 2.x Error Handling:

Output:

Python 3.x Error Handling:

Output:

5. Xrange

The xrange() function of python 2.x is removed in python 3.x. Instead, the behavior and properties of xrange() are incorporated into the range() function in python 3.x

The range() function of python 2.x returns a list of elements. For example. range(4) returns [0, 1, 2, 3] whereas the xrange() function in python 2.x returns an iterator object which we can loop through to get the range of numbers. The difference between the range() and xrange() in python 2.x is that If we need to iterate over the same sequence multiple times, we prefer range() as range provides a static list. xrange() reconstructs the sequence every time. Also, xrange() function does not support the slices and other list methods as the return type is not a list. However, xrange() function saves memory if the task is to iterate over a large range as it constructs the sequence dynamically i.e it will compute the next value in the sequence only when needed, unlike range() which generates and returns a static list. So in terms of memory xrange() is optimal whereas in terms of speed range() is faster.

In python 3.x the range() function does what xrange() does in python 2.x, so essentially the xrange() function in python 2.x is now the range() function in python 3.x and there is no xrange() function in python 3.x.

Python 2.x xrange:

Output:

Python 3.x range:

Output:

6. Raising Exception

The syntax for raising an exception is modified in python 3.x. Below is the 3.x and 2.x syntax for raising exceptions

Python 3.x syntax:

Only the above syntax will work in python 3.x. Below is the syntax for Python 2.x

Python 2.x syntax:

The above syntax will throw an error in python 3.x, however, the parentheses syntax of python 3.x will work in 2.x.

7. List Comprehension Loop Variables

In python 2, if you give the name of the variable that is iterated over in for loop list comprehension and also used the same name for a global variable, then the values of the global variable will get updated because of the variable with the same name that is iterated in the for loop list comprehension which should not be the case. This issue is fixed in python 3. The variable used to iterate in the for loop is treated as a local variable inside the for loop and the global variable with the same name won’t be affected.

Python 2.x list comprehension:

Output:

Notice, the global variable x got modified after the iterator x inside the for loop is changed. Now let us examine the same in python 3.x

Python 3.x list comprehension:

Output:

We can see from the output that the global variable x values remain unchanged after the for loop iteration in the list comprehension.

8. Future Modules

This is not exactly a difference between python 2.x and 3.x but is something present in python 2.x that 3.x doesn’t need to have. The future module is simply a python module that we can import in our python 2.x code to implement the python 3.x behavior. So if we are planning to support a behavior that is present in python 3.x in our python 2.x code we can make use of this future module in python 2.x. Take a look at the below examples to understand this better.

Example #1: To implement the behavior of print function present in python 3.x to python 2.x

Output:

In the above program, the print function of python 3.x is implemented into the python 2.x code because we imported the print_function from the future module.

Example #2: To implement the behavior of integer division present in python 3.x to python 2.x

Output:

In the above program, the integer division behavior of python 3.x is implemented in python 2.x because we imported the division from the future module.

Conclusion

As python 3.x is backward-incompatible(code in python 3.x will not compile with a python 2.x compiler, you’ll need a python 3 compiler ) it is needed for anyone who is working with multiple versions of python like 2.7 and 3.9 to be aware of the changes between the versions as some of the issues that can arise may not even be found during compilation( like integer division ).

Read More:

  1. Hello World Program in Python.
  2. Python First Program.
  3. Print Function in Python.
  4. Comprehension in Python .
  5. union() in python.