-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhidden_python_features.py
More file actions
66 lines (44 loc) · 1.54 KB
/
hidden_python_features.py
File metadata and controls
66 lines (44 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#! 1. Anonymous variables
items = [['a', 'b'], ['c', 'd'], ['e', 'f']]
# to get only the second variable and have better readability
seconds = [x for _, x in items]
print(seconds)
#! 2. For-Else loop and While-Else loop to recognize early breaks whne a condition is met
items = [chr(ord('a')+i) for i in range(6)]
i=0
while i < len(items):
if items[i] == 'c':
print('found it')
break
i+=1
else:
print("not found")
#! 3. Walrus operator := -> allows you to define and simulatenously use the variable in a condition
# example
def get_data():
for i in range(10):
yield i
yield -1
gen = get_data()
while (data := next(gen)) != -1:
print(data)
# another example to avoid recomputing or re-calling a function which could be computationally expensive
def f(x): # asumme this is a very expensive function
return x-1
results = [f(x) for x in range(10) if f(x) > 3] # this calls f(x) twice for each value which is stupid
results_walrus = [result for x in range(10) if (result := f(x)) > 3] # ! this is better
print(results)
#! 4. Arguement unpacking -> use `*` to unpack items ƒrom an iterable obj
def print_nums(a, b, c, d):
print(a, b, c, d)
lst = [1, 2,3 , 4]
print_nums(*lst)
#! 5. defaultdict for handling access to keys that dont exist in a dict with a default value
from collections import defaultdict
def default():
return 0
char_count= defaultdict(default)
string = 'adfijneiuwnkasdfnskjdfn'
for char in string:
char_count[char]+=1
print(char_count)