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
`http://stackoverflow.com/questions/10508021/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
`http://stackoverflow.com/questions/1517616/stream-large-binary-files-with-urllib2-to-file#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              fp.write(chunk)``#no module named urllib2 in python3`
3. How do you split a list into evenly sized chunks

http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python

#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

http://stackoverflow.com/questions/2068372/fastest-way-to-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]:

sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1)

return  + [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`
`http://stackoverflow.com/questions/1323410/has-key-or-in`
`d = {'a': 1, 'b': 2}`
`d.has_key('a')`

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

`install_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:

pass

#versions (<=2.5)

except (Exception1, Exception2), e:

pass

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