A lot of people Google for Stackoverflow answers to their questions but struggle sometimes to make the code sample & answer work in their environment, We decided to examine some code sample answers to Stack Overflow questions that do not work in Python v3.x . 

This is a part of Python Knowledge and Resources List

  1. Matrix multiplication in python


    #versions (2.x)

    def matmult(a,b):

        zip_b = zip(*b)

        return [[sum(ele_a*ele_b for ele_a, ele_b in zip(row_a, col_b)) for col_b in zip_b] for row_a in a]

    #zip returns an iterator in python 3.x so
    #versions (3.x)

    def matmult(a,b):

        zip_b = zip(*b)

        zip_b = list(zip_b)

        return [[sum(ele_a*ele_b for ele_a, ele_b in zip(row_a, col_b))

                 for col_b in zip_b] for row_a in a]

  2. Stream large binary files


    #versions (only 2.x)

    req = urllib2.urlopen(url) 

    CHUNK = 16 * 1024 

    with open(file, 'wb') as fp:

           while True: 

                 chunk = req.read(CHUNK) 

                 if not chunk: break 


    #no module named urllib2 in python3
  3. How do you split a list into evenly sized chunks


    #versions (2.7)

    def chunks(l, n):

        """ Yield successive n-sized chunks from l. """

        for i in xrange(0, len(l), n):

            yield l[i:i+n]

    #no need for xrange in python 3.x as range itself returns an iterator

    #versions (3.x)

    def chunks(l, n):

        for i in range(0, len(l), n):

            yield l[i:i+n]

  4. List all primes below N


    #versions (2.x)

    def primes(n):

       """ Returns  a list of primes < n """

       sieve = [True] * n

       for i in range(3,int(n**0.5)+1,2):

           if sieve[i]:


       return [2] + [i for i in xrange(3,n,2) if sieve[i]]

  5. Fibonacci generator

    a = int(raw_input('Give amount: '))
    def fib(n):
        a, b = 0, 1
        for _ in xrange(n):
            yield a
            a, b = b, a + b

    print list(fib(a))

    #raw_input() and xrange() are not defined in python 3 use input() and range() insted
  6. haskey()
    d = {'a': 1, 'b': 2}

    #python3 dicts have no has_key
  7. Print on same line
    def install_xxx():
       print("Installing XXX...      "),

    print "[DONE]"

    #print is a statement in 2.x while its a function in python 3.x
  8. Catch multiple exceptions in one line


    #versions (>2.6)

    except (Exception1, Exception2) as e:


    #versions (<=2.5)

    except (Exception1, Exception2), e:


Add a Resource to this List
Not more than 250 characters.