Python 2.x and Python 3.x: key differences

Why are there two version of Python?

Change has been afoot for some time in the land of Python, however. The Python Software Foundation, released version 2.7 in 2010, while at the same time upgrading the codebase to various iterations of 3.x simultaneously. Over a number of years, companies and projects started migrating to Python 3 due to its various benefits.

Python 2 vs 3 – Difference between Python 2 and 3

 Python 2Python 3
1. Integer Divisionprint 9/2

>> 4

print(9/2)

>> 4.5

2. Print functionprint “Hello world”

>>Hello world

print(“Hello world”)

>>Hello world

3. Unicodeprint type(Unicode(“Hello”))

>>  <type ‘unicode’>

 print type(b’Hello’)

>> <type ‘str’>

 print ‘hello’ +  b’ world’

>>hello world

 print type(bytearray(b’hello world’))

>> <type ‘bytearray’> 

print (‘\u03BCnico\u394e!’)

>> unicode!

 print(type(b’hello’))

>> <class ‘bytes’>

 print(‘hello’ + b’ world’))

>> TypeError

 print(type(bytearray(b’hello’)))

>> <class ‘bytearray’>

4. xrange functionSupport range() and xrange() both.have no xrange() function but range() function will behave like xrange() in python 2.
5. Raising exceptionraise IOError, “file not found”

>>IOError: file not found

raise IOError(“file not found”)

>>IOError: file not found                           

6. Handling exceptiontry:

print 4/0

except ZeroDivisionError, err:

  print “can’t divide by zero”

  print “error – “ + err

output:

can’t divide by zero

error – integer division or modulo by zero

try:

print(4/0)

except ZeroDivisionError as err:

  print(“can’t divide by zero”)

  print(“error –“ + str(err))

output:

can’t divide by zero

error – division by zero

7. Leak of for-loop variables in global namespacei = 1

print ‘before: i = ‘, i

print ‘loop:’,[i for i in range(5)]

print ‘after:i = ‘, i

Output:

before: i =1

loop: [0,1,2,3,4]

after: i = 4

i = 1

print(‘before :i =’, i)

print(‘loop:’ [i for i in range(5)])

print(‘after: i = ‘, i)

Output:

before: i = 1

loop: [0,1,2,3,4]

after: i = 1

8. .next() methodhave next() function and .next() method for iterate next element.

list1 = [4, 43, 34,  32]

iterator = iter(list1)

print iterator.next()

print next(iterator)

print iterator.next()

Output:

4

43

34

Have only next() function.

list1 = [4, 43, 34, 32]

iterator = iter(list1)

print (next(iterator))

print (next(iterator))

print (next(iterator))

Output:

4

43

34

9. input() methodWe can use both raw_input() and input() method.

s = raw_input(“enter something:”)

raw_input() is replaced by input() method. There is no raw_input() method.

s = input(“enter something:”)

Let’s understand these differences in detail.

1. Integer Division:-

In python 2 if we perform division on two integers then the output will be an integer too. But in python 3, output will be accurate, so the result can be in float too. Still want the result in integer, then you can use print(9//2) it return an integer result.

2. Print Function:-

In python 2 parenthesis aren’t compulsory to use we can print anything without using parenthesis but in Python 3 it is compulsory to use parenthesis otherwise it will raise error.

3. Unicode:-

Python 2 has ASCII str() Types, separate Unicode but it doesn’t have byte type.

But in Python 3 we have Unicode (utf-8: 8 means it uses 8-bit block to represent a character) strings and also 2 byte classes that are bytearray and byte.

Python 2 treats string and bytes as same, so we can also concatenate them. But in Python 3 we can’t concatenate a byte array with strings, because both are different for python 3.

4. xrange function:-

python 2 has two handy function for creating a range of integers  that is used in for loop, these are range and xrange. They both provide a way to generate a list of integers. So for the most part, xrange and range are the exact same in terms of functionality. The only difference is that range returns a Python List object and xrange returns an xrange object. range function creates an array of integers, so it will take much memory if we create a range of millions, which can result MemoryError and crash your program. So xrange is the function to use if you’ve a really memory sensitive system such as cell phone.

But in python 3 there is no xrange function, the range function will work as xrange in python 2.

Example:

#program in python 3

for i in range(1,10):

  print(i)

#program in python 2

for i in xrange(1,10):

  print i

Output

1

2

3

4

5

6

7

8

9 

5. Raising exception:-

as we’ve seen the difference between print function, raising an exception will follow the same syntax.

In python 2, its

raise IOError, “file not found”

In python 3, its

raise IOError(“file not found”)

6. Handling exception:-

there is a minor change in syntax, we’ve to use as keyword in python 3.

In python 2, its

except IOError, err:

In python 3, its

except IOError as err: 

7. Leak of for-loop variables in global namespace:-

In python 2 there was a problem that value of a global variable had changed while using that variable in for-loop.

But in Python 3, for loop variables don’t leak into the global namespace anymore!

8. .next() method:-

Python have .next() method and next() function to fetch the next element of an iterator.

But in python 3 .next() method is no more. We have to use only next() function to iterate the next element of iterator.

9.input() method:-

python 2 have input() and raw_input() methods for taking input. The difference between them raw_input() returns a string, and input() tries to run the input as a python expression.

Mostly all we want the string as input then we convert it into any datatype as we want.

In python 3 there is no raw_input() method. The raw_input() method is replaced by input() in python 3. If you still want to use the input() method like in python 2 then we can use eval() method.

eval(input(“enter something:”))

it will work as same as input() in python 2.

There are many other differences between python 2 and python 3 like

10. The __future__ Module:-

as we know there are many things that python 3 supports but python 2 don’t. if you’re planning python 3 support for your code then use __future__ module.

Let’s say we want python 3’s integer division behavior in our python 2 program then our program will look like

from  __future__ import division

print 9/2

output:

4.5

without __future__ module

Print 9/2

Output:

4 

11. Libraries:-

The advantage to use python 2 is it have a large number of libraries. Python 2 is still the default in many operating systems like ubuntu 14.04 and 16.04 LTS. But python 3 is also developing day by day, all the future developments will be implement in python 3 rather than the python 2.

So if you’re completely beginner then we recommend python 3 because it is the future of Python and it is easy as python 2 to learn and python 3 has some additional features (eg. Function memoiziation).

Comment below if you have queries related to above tutorial for difference between python 2 and 3.

Why I recommend Python 3.x ? 

Python 2 vs 3 performance in terms of computing speed has been dramatically improved, but Python 3 also improves upon the already vast abilities of Python 2.

To put it bluntly, Python 2 is legacy, Python 3 is the Future. If you are starting to learn to code — learn Python 3. Here are some additional reasons why you should learn Python 3:

  • Legacy code. After 2020, Python 2 will no longer be maintained. 
  • Learn best-practices. Python 3 includes upgrades not available in Python 2.
  • Write cleaner code. Python 3 has elegantly modified its structure to so that it takes fewer lines of code to perform an action.
  • Avoid syntax confusion. Some small grammatical differences exist between the two versions, which can frustrate beginners.
  • Easier user input. A common early lesson is to take a user’s typed-in data (the input syntax example used above, for instance) and pass it off to a simple script to create a list of information. Python 3 improves upon this process.
  • Improved number management. Python 3 includes some math-calculation improvements that are critical for many applications.
  • Popular add-ons are supported. You’ll also learn the concept of extensions called “modules” and “packages” that are not included in the default Python 3 installation. As you grow, installing and using these will become part of your daily repertoire. Nearly all of the most popular packages have been Python 3-ready for years.
  • Unicode support. Did you know that emojis are Unicode characters? No emojis in Python 2! ? ? ?

Some Major Changes are:-

Python  2.x

  • Print functional brackets are optional.
  • Prefix string with u to make Unicode string.
  • Division of integers always returns integer - 5/2=2.
  • Raw_input () reads string.
  • input() evaluates data read.
  • generator .next().

Python  3.x

  • Print functional brackets are compulsory.
  • String Unicode by default.
  • Division of integers may result in the float - 5/2=2.5.
  • Raw_input() not available.
  • Input always reads the string.
  • Next (generator).
  • Py2 to a py3 utility.
  • Dictionary .keys() and .values() returns a view not a list.
  • Can no longer use comparison operators on non natural comparisons.

Summary

I hope you have enjoyed reading. We have covered all the basic differences between Python 2 and Python 3, so you can start practicing now. Happy learning.

Tags