Open In App

Python2 vs Python3 | Syntax and performance Comparison

Last Updated : 28 Oct, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

Python 2.x has been the most popular version for over a decade and a half. But now more and more people are switching to Python 3.x. Python3 is a lot better than Python2 and comes with many additional features. Also, Python 2.x is becoming obsolete this year. So, it is now recommended to start using Python 3.x from now-onwards.

Still in dilemma?
Ever wondered what separates both of them? Let’s find this thing out below.

First of all, let us go through this quick comparison through this image, which will give you a fair idea on what to expect.

Print Statement

Python 2.7: Extra pair of parenthesis is not mandatory in this.




print 'Hello and welcome to GeeksForGeeks'


Python 3.x: Extra pair of parenthesis is mandatory.




print ('Hello and welcome to GeeksForGeeks')


Integer Division

Python 2.7:
The return type of a division (/) operation depends on its operands. If both operands are of type int, floor division is performed and an int is returned. If either operand is a float, a classic division is performed and a float is returned. The // operator is also provided for doing floor division no matter what the operands are.




print 5 / 2
print -5//2
  
# Output:
# 2
# -3


Python 3.x:
Division (/) always returns a float. To do floor division and get an integer result (discarding any fractional result) you need to use // operator.




print (-5 / 2)
print (5//2)
  
# Output:
# -2.5
# 2


Input Function

Python 2.7:
When you use input() function, Python automatically converts the data type based on your input.




val1 = input("Enter any number: ")
val2 = input("Enter any string: ")
  
type(val1)
type(val2)


raw_input gets the input as text (i.e. the characters that are typed), but it makes no attempt to translate them to anything else; i.e. it always returns a string.




   
val1 = raw_input("Enter any number: ")
val2 = raw_input("Enter any string: ")
  
type(val1)
type(val2)


Python 3.x
In Python3, the input function acts like raw_input from Python 2.7 and it always returns string type.




val1 = input("Enter any number: ")
val2 = input("Enter any string: ")
  
type(val1)
type(val2)
# In order to fix this you need to apply 
# float() function when user is prompted for input.


Round Function

Python 2.7: The output always results in a floating point number.




print(round(69.9))  
print(round(69.4))
  
# Output: 
# 70.0
# 69.0


Python 3.x: The return results in n digit precision.




print(round(69.9))  
print(round(69.4))
  
# Output:
# 70
# 69


List Comprehensions

Python 2.7: Refer to the example below, how global variable changes.




num = 7
print (num)
  
mylist = [num for num in range(100)]
print (num)
  
# Output:
# 7
# 99


Python 3.x: There is no namespace leak now. This is quite fixed now.




num = 7
print (num)
  
mylist = [num for num in range(100)]
print (num)
  
# Output: 
# 7
# 7


Range Function

Python 2.7 :
It has both range and xrange function. When you need to iterate one object at a time, use xrange and when you need an actual list, use range function. xrange is generally faster & saves memory.




% timeit [i for i in range(1000)]  
% timeit [i for i in xrange(1000)]


Python 3.x :
Here range does what xrange does in Python 2.7. xrange doesn’t work in Python 3.x.




% timeit [i for i in range(1000)]  
% timeit [i for i in xrange(1000)]


Exception Handling

Python 2.7 : This has a different syntax than Python 3.x.




try:
    YoYo
except NameError, error:
    print error, "YOU HAVE REACHED FOR AN ERROR"
  
try:
    YoYo
except NameError as error:
    print error, "YOU HAVE REACHED AN ERROR, YET AGAIN !"


Python 3.x: ‘As’ keyword is needed to be included in this.




try:
    YoYo
except NameError as error:
    print (error, "THE ERROR HAS ARRIVED !")


List Comprehensions

Python 2.7: Lesser parenthesis than Python 3.x.




[item for item in 1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]


Python 3.x: Extra pair of parenthesis is needed here.




[item for item in (1, 2, 3, 4, 5)]
[1, 2, 3, 4, 5]


next() function and .next() method

Python 2.7: Both next() and .next() are used here.




generator = (letter for letter in 'abcdefg')
next(generator)
generator.next()


Python 3.x: Only next() is used here. Using .next() shows an AttributeError.




generator = (letter for letter in 'abcdefg')
next(generator)


ASCII, Unicode and Byte types

Python 2.7: It has ASCII string type, a separate unicode type, but there is no byte type.




type(unicode('a'))
type(u'a')
type(b'a')


Python 3.x: We have unicode strings, and byte type.




type(unicode('a'))
# This returns an error


Note: List of Methods & Functions that don’t return list anymore in Python 3.x.

In Python2.x - 

zip()
map()
filter()
dictionary’s .keys() method
dictionary’s .values() method
dictionary’s .items() method


Similar Reads

How to create an instance of a Metaclass that run on both Python2 and Python3?
Metaclasses are classes that generate other classes. It is an efficient tool for class verification, to prevent sub class from inheriting certain class function, and dynamic generation of classes. Here we will discuss how to create an instance of a Metaclass that runs on both Python 2 and Python 3. Before delving into it, let's go through the code
3 min read
Automate the Conversion from Python2 to Python3
We can convert Python2 scripts to Python3 scripts by using 2to3 module. It changes Python2 syntax to Python3 syntax. We can change all the files in a particular folder from python2 to python3. Installation This module does not come built-in with Python. To install this type the below command in the terminal. pip install 2to3 Syntax: 2to3 [file or f
1 min read
Upgrading from Python2 to Python3 on MacOS
Python is a high level and general-purpose programming language. It is widely used in a variety of fields such that it fulfills the need of developers who are in the front end, backend, or both. It is being used rigorously in Machine Learning, Artificial Intelligence, Web Development, and in various other domains. But, there's an issue that mac dev
4 min read
Python3 Program to Rearrange array such that arr[i] >= arr[j] if i is even and arr[i]<=arr[j] if i is odd and j < i
Given an array of n elements. Our task is to write a program to rearrange the array such that elements at even positions are greater than all elements before it and elements at odd positions are less than all elements before it.Examples: Input : arr[] = {1, 2, 3, 4, 5, 6, 7} Output : 4 5 3 6 2 7 1 Input : arr[] = {1, 2, 1, 4, 5, 6, 8, 8} Output : 4
3 min read
Python3 Program for Check if an array is sorted and rotated
Given an array of N distinct integers. The task is to write a program to check if this array is sorted and rotated counter-clockwise. A sorted array is not considered as sorted and rotated, i.e., there should at least one rotation.Examples: Input : arr[] = { 3, 4, 5, 1, 2 } Output : YES The above array is sorted and rotated. Sorted array: {1, 2, 3,
3 min read
How to install Python3 and PIP on Godaddy Server?
GoDaddy VPS is a shared server that provides computational services, databases, storage space, automated weekly backups, 99% uptime, and much more. It’s a cheaper alternative to some other popular cloud-based services such as AWS, GPC, and Azure. Python is an open-source, cross-platform, high-level, general-purpose programming language created by G
2 min read
Different Input and Output Techniques in Python3
An article describing basic Input and output techniques that we use while coding in python. Input Techniques 1. Taking input using input() function -> this function by default takes string as input. Example: C/C++ Code #For string str = input() # For integers n = int(input()) # For floating or decimal numbers n = float(input()) 2. Taking Multipl
3 min read
Python3 Program to Find Maximum number of 0s placed consecutively at the start and end in any rotation of a Binary String
Given a binary string S of size N, the task is to maximize the sum of the count of consecutive 0s present at the start and end of any of the rotations of the given string S. Examples: Input: S = "1001"Output: 2Explanation:All possible rotations of the string are:"1001": Count of 0s at the start = 0; at the end = 0. Sum= 0 + 0 = 0."0011": Count of 0
5 min read
Python3 Program to Minimize characters to be changed to make the left and right rotation of a string same
Given a string S of lowercase English alphabets, the task is to find the minimum number of characters to be changed such that the left and right rotation of the string are the same. Examples: Input: S = “abcd”Output: 2Explanation:String after the left shift: “bcda”String after the right shift: “dabc”Changing the character at position 3 to 'a' and c
3 min read
Python3 Program for Longest subsequence of a number having same left and right rotation
Given a numeric string S, the task is to find the maximum length of a subsequence having its left rotation equal to its right rotation. Examples: Input: S = "100210601" Output: 4 Explanation: The subsequence "0000" satisfies the necessary condition. The subsequence "1010" generates the string "0101" on left rotation and string "0101" on right rotat
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg