How to replace elements in a list using dictionary lookup

If all values are unique then you should reverse the dict first to get an efficient solution: >>> subs = { … “Houston”: “HOU”, … “L.A. Clippers”: “LAC”, … … } >>> rev_subs = { v:k for k,v in subs.iteritems()} >>> [rev_subs.get(item,item) for item in my_lst] [‘L.A. Clippers’, ‘Houston’, ’03/03 06:11 PM’, ‘2.13’, ‘1.80’, ’03/03 … Read more

Python 3 range Vs Python 2 range

Python 3 uses iterators for a lot of things where python 2 used lists.The docs give a detailed explanation including the change to range. The advantage is that Python 3 doesn’t need to allocate the memory if you’re using a large range iterator or mapping. For example for i in range(1000000000): print(i) requires a lot … Read more

Efficiently filtering out ‘None’ items in a list comprehension in which a function is called

Add an if into your comprehension like: l = [y for y in (f(x) for x in [1,2,3,4]) if y is not None] By placing a Generator Expression inside the list comprehension you will only need to evaluate the function once. In addition the generator expression is a generator so takes no extra intermediate storage. … Read more