Published on

16. Compare Python 2.x and 3.x

Authors

16. Please point out a few differences between Python 2.x and 3.x?

Here are some key differences between Python 2.x and Python 3.x, especially relevant if you're migrating or maintaining legacy code:


1. Change in the Printing Syntax

Python 2:

print "Hello"  # valid

Python 3:

print("Hello")  # ✅ print is a function now
  • Why the change? To make print consistent with function syntax and extensible (e.g., print(file=...), print(end='')).

2. Change in Integer Division Behavior

Python 2:

print 3 / 2  # Output: 1 (floor division for integers)

Python 3:

print(3 / 2)  # Output: 1.5 (true division)
  • Use // for floor division in both versions:
print(3 // 2)  # Output: 1
  • Why the change? Python 3 emphasizes clarity and math correctness/ always means real division.

3. Introduction of Unicode and Two Byte Classes

Python 2:

  • str is a byte string.
  • unicode is a separate type.
type("hello")     # <type 'str'>
type(u"hello")    # <type 'unicode'>

Python 3:

  • All str are Unicode.
  • bytes is a separate type.
type("hello")     # <class 'str'> (Unicode)
type(b"hello")    # <class 'bytes'>
  • Why the change? Unicode is essential for modern, internationalized software.

4. New __contains__ Method for range Object

Python 2:

r = xrange(1000000)
999999 in r  # slow, iterates through elements

Python 3:

r = range(1000000)
999999 in r  # ✅ fast, uses __contains__
  • range is now a lazy, iterable object with efficient indexing and membership testing.
  • Why the change? For memory efficiency and faster lookups in large ranges.

5. Enforced Syntax for Raising Exceptions

Python 2:

raise IOError, "file not found"  # valid in 2.x

Python 3:

raise IOError("file not found")  # ✅ must use parentheses
  • Why the change? Makes exception raising consistent and object-oriented.

6. Deprecation of the .next() Method

Python 2:

it = iter([1, 2, 3])
it.next()  # valid in 2.x

Python 3:

it = iter([1, 2, 3])
next(it)   # ✅ must use built-in `next()` function
  • .next() is removed in Python 3 for consistency with other iterator types.

7. TypeError on Unorderable Comparisons

Python 2:

print([] < {})  # Output: True or False, arbitrarily allowed

Python 3:

print([] < {})  # ❌ TypeError: unorderable types
  • Why the change? Comparisons between unrelated types are logically meaningless and error-prone, so Python 3 rightly forbids them.

✅ Summary Table:

ChangePython 2Python 3
Print syntaxprint "Hi"print("Hi")
Integer division3 / 2 = 13 / 2 = 1.5
Unicode handlingASCII str, separate unicodeUnicode str, separate bytes
Range lookup (__contains__)Slower with xrangeFast with range
Raise exception syntaxraise IOError, "msg"raise IOError("msg")
.next() methodit.next()next(it)
Comparing unorderable typesAllowed (inconsistent)Raises TypeError