Python 2 and Python 3 Difference

By Xah Lee. Date: . Last updated: .

The major differences between python 2 and 3 is that python 3 made string into a Unicode type.

This has major consequences. It is not trivial to convert non-trivial python software from python 2 to 3. (say, code that's more than say 1k lines.)

Python 3 also introduced lots other minor changes.

Here's a list of the major notable differences.

String is Now Unicode Character

In python 2, a string of this syntax "abc" is type str, and it basically holds bytes, or ASCII characters. [see ASCII Table] For unicode string, its syntax is u"abc", and type is unicode.

print type("abc")
# <type 'str'>

print type(u"abc")
# <type 'unicode'>

In python 3, string are now unicode characters. Its type is unicode. You don't need to use the u in u"…".

print( type ("abc") )
# <class 'str'>

This change, is not just about syntax, but has pervasive impact on the language. If your code deal with string and byte a lot, it's not trivial to convert to python3.

Print is Now a Fuction

In python 2, print is a statement, no need parenthesis: print arg1, arg2, ….

In python 3, print is a function, need parenthesis, like this: print(arg1, arg2, …).

Separator and ending char can be specified.

print( "a", "b", sep=",", end=",")
print( "c")
# prints
# a,b,c

Division of Integers

In python 2, 3/2 return 1.

In python 3, 3/2 return 1.5

The division operator automatically convert integers to float.

To get floor division, use //, example: 3//2 → 1.

Map Returns a Iterator

Many functions that used to return list in python 2 now returns iterator instead.

They include:

The following in python 2 are removed:

To get a list from iterator, call list(iter)

In python 2, map returns a list.

x = map(lambda x:x+1, [3,4,5])
print x # [4, 5, 6]

In python 3, map returns a iterator.

x = map(lambda x:x+1, [3,4,5])
print(x) # <map object at 0x10403a3c8>

xrange gone

python 2 have range and xrange

range returnes a list, xrange returnes a iterator object.

x = range(3)

print x
# [0, 1, 2]

print type(x)
# <type 'list'>

y = xrange(3)

print y
# xrange(3)

print type(y)
# <type 'xrange'>

python 3 only have range, it returns a iterator object.

x = range(3)

print(x)
# range(0, 3)

# convert it to list
print(list(x))
# [0, 1, 2]

print(type(x))
# <class 'range'>

file() function gone

file() function is gone. use open() instead.

raw_input gone

python 2 have raw_input() and input()

python 3 only have input()

.next() method gone

python 2 have .next() method and next() function.

python 3 only have next() function.

x = iter([3,4,5])
print( next(x) ) # 3

Leaked Var in List Comprehension

in python 2, variable name in list comprehension will leak if there's a global variable of the same name.

x = 1
[ x+1 for x in [1,2,3]]
print( x ) # 3

fixed in python 3.

x = 1
[ x+1 for x in [1,2,3]]
print( x ) # 1

Raising Exceptions

raise IOError, "wrong"
raise IOError("wrong")

urllib module rename

The urllib module has been split and renamed to:

Convert python 2 to 3

Use the tool at /usr/bin/2to3. It is installed if you have python3 installed.

2to3 filename

It's helpful for small scripts, or to get an idea which part needs to change.

Here's a example python 2 to python 3 conversion differences, just to give a idea.

-            os.makedirs(dirName,0775)
+            os.makedirs(dirName,0o775)

-    u"""Generate thumbnail images.
+    """Generate thumbnail images.

-    print '</a>'
+    print('</a>')

-    txt_segs = re.split( re.compile(r'src', re.U|re.I), unicode(FF.read(), 'utf-8'))
+    txt_segs = re.split( re.compile(r'src', re.U|re.I), str(FF.read(), 'utf-8'))

-        match_result = re.search(ur'\s*=\s*\"([^\"]+)\"', link_block, re.U)
+        match_result = re.search(r'\s*=\s*\"([^\"]+)\"', link_block, re.U)

-    for im in filter(lambda x : (not x.startswith('http')) and (not x.endswith('icon_sum.gif')), get_inline_img_paths(dPath + '/' + fName)):
+    for im in [x for x in get_inline_img_paths(dPath + '/' + fName) if (not x.startswith('http')) and (not x.endswith('icon_sum.gif'))]:

If you have a question, put $5 at patreon and message me.

Python

  1. Python 3 Basics
  2. Python 2 Basics
  3. Python 2 and 3 Difference
  4. Print Version
  5. Builtin Help
  6. Quote String
  7. String Methods
  8. Format String
  9. Operators
  10. Complex Numbers
  11. True, False
  12. if then else
  13. Loop
  14. List Basics
  15. Loop Thru List
  16. Map f to List
  17. Copy Nested List
  18. List Comprehension
  19. List Methods
  20. Sort
  21. Dictionary
  22. Loop Thru Dict
  23. Dict Methods
  24. Tuple
  25. Sets
  26. Function
  27. Closure
  28. 2 Closure
  29. Decorator
  30. Class
  31. Object, ID, Type
  32. List Modules
  33. Write a Module
  34. Unicode 🐍

Regex

  1. Regex Basics
  2. Regex Reference

Text Processing

  1. Read/Write File
  2. Traverse Directory
  3. File Path
  4. Process Unicode
  5. Convert File Encoding
  6. Find Replace in dir
  7. Find Replace by Regex
  8. Count Word Frequency

Web

  1. Send Email
  2. GET Web Page
  3. Web Crawler
  4. HTTP POST

Misc

  1. JSON
  2. Find Script Path
  3. Get Env Var
  4. System Call
  5. Decompress Gzip
  6. Append String in Loop
  7. Timing f timeit
  8. Keyword Arg Default Value Unstable
  9. Check Page Load Size
  10. Thumbnail Generation