Please enable JavaScript.
Coggle requires JavaScript to display documents.
python (1. Pythonic Thinking
Item 3
Python3
Seq of chars represented…
python
1. Pythonic ThinkingItem 3
Python3
Seq of chars represented by -
- Str - Unicode chars
- Bytes - Raw 8 bit values
Python 2
- Str -
- Unicode -
Recomm - Use Str in Py3 and unicode in Py2
-
Item 4
Writing Helper fn
- Move complex sigle line expressions to helper
- Use if/else to be more clear
Item 5
- Slice sequences
a[Start:stop]
a=[1,2,3,4,5,6]
a[1,3] => [2,3] stop at index 3 and do not include it.
-
Item 7
Use List comprehensions instead of Map & filter
- a= [1,2,3,4]
squares = [x**2 for x in a]
Filtering is easy with comprehensions
- even_sq = [x**2 for x in a if x%2 ==0]
Dict & Sets also support comprehension
- ranks = {'neil':1,'mukesh':2}
- rank = {rank:name for name, rank in ranks.items() }
- rank_set = {len(name)for name in rank_set.values()}
Item 8
- Avoid > 2 comprehensions in a list
Item 9
Use generator expression for large expression in a list
- Put comprehension code in brackets ()
- It evaluated to an iterator and do not loop
a=[1,2,3,4,5]
squares= (x**2 for x in a)
print(next(squares))
Item 10
Prefer Enumeration over range
a=['hi','bye']
- for index,val enumerate(a)
Item 11
Use zip to iterate in parallel
- zip in 3 returns generator
Item 12
- for i in range(3):
print ...
if (i==1):
break
else:
print "bye"
When code hits break it falls in else.
If it doesn't then it will not fall in else.
Item 13
- Try /except/ else/finally
When try doesn't raise exception, else handles it.
Item 14
- Prefer Exceptions instead of returning None
def divide(a,b):
try:
return a/b
except ZeroDivisionError:
return None
*Above code could cause issues if the caller checks like
if not divide(a,b): ...
Instead
Item 15
Variable scope in closure
- Functions are first class objects in Python
- They can be referred to directly
- Assign to variables
- Pass as arguments to other functions
Getting data out of Closure
nonlocal statement
-
-
Item 18
Prefixing last param with "*" makes it optional
This to save from passing empty objects like list when there is nothing to pass
-