We evaluated Stack Overflow for the most frequent problems encountered by people & summarized the answers as well.
1. How do I check if a file exists, using Python, without using a try statement?
(compatible with python 2.x/3)
import os
print os.path.isfile(fname)
2. Best way to check if a list is empty
(2.x/3)
li=[]
if not li:
print “empty"
3. Nicest way to pad zeros to string
(2.7/3.x compatible)
“12345”.zfill(10)
4. How to know if an object has an attribute in python
hasattr(a,’attributename’)
(2.7/3.x compatable)
5. Catch Multiple Exceptions in one line
(>2.6)
except (Exception1, Exception2) as e:
pass
6. How to list all files of a directory in python ?
(2.7/3 compatible)
import os
os.listdir()
7. How do i sort a list of Dictionaries by values of Dictionaries ?
(python 2.x and 3.x compatible)
newlist = sorted(list_to_be_sorted, key=lambda k: k['name'])
8. How do you split a list into evenly sized chunks ?
def chunks(l, n):
""" Yield successive n-sized chunks from l. """
for i in xrange(0, len(l), n):
yield l[i:i+n]
9. How do i download a file over HTTP ?
import urllib2
urllib2.urlopen('http://www.example.com/').read()
10. Matrix multiplication in Python?
(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]
11. list all primes below N
(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 [2] + [i for i in xrange(3,n,2) if sieve[i]]
12. Binary search algorithm in python
def binary_search(array, target):
lower = 0
upper = len(array)
while lower < upper: # use < instead of <=
x = lower + (upper - lower) // 2
val = array[x]
if target == val:
return x
elif target > val:
if lower == x: # this two are the actual lines
break # you're looking for
lower = x
elif target < val:
upper = x