Python-a11-pythonic

This article shows the examples of pythonic in python

replace map, filter by list comprehension

1
2
3
4
5
6
7
8
# no pythonic
nums = [1, 2, 3, 4, 5]
result = map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, nums))
print(list(result)) # [4, 16]

# pythonic
result2 = [x ** 2 for x in nums if x % 2 == 0]
print(list(result2)) # [4, 16]

replace list comprehension by generator expression

Generator expression takes less memory than list comprehension

1
2
3
4
5
6
# no pythonic
my_comp = [x * 5 for x in range(1000)]
print(getsizeof(my_comp)) # 8856
# pythonic
my_gen = (x * 5 for x in range(1000))
print(getsizeof(my_gen)) # 112

using of enumerate

1
2
3
4
5
6
7
8
9
10
11
12
# no pythonic
fruits = ['apple','banana', 'orange']
for i in range(len(fruits)):
print(fruits[i], ':', i) # apple : 0
# banana : 1
# orange : 2

# pythonic
for i, v in enumerate(fruits):
print(v, ':', i) # apple : 0
# banana : 1
# orange : 2

use with

With the ‘with’ statement, we get better syntax and exception handing

1
2
3
4
5
6
7
8
9
# no pythonic
f = open('test.txt')
try:
data = f.read()
finally:
f.close() # we have to close the file by ourself
# pythonic
with open('test.txt') as f:
data = f.read() # python close the file for us

use zip

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# no pythonic
a = [1, 5, 7]
b = [2, 4, 6]
for i in range(len(a)):
if a[i] > b[i]:
print(a[i])
else:
print(b[i]) # 2
# 5
# 7
# pythonic
a = [1, 5, 7]
b = [2, 4, 6]
for i, j in zip(a, b):
if i > j:
print(i)
else:
print(j) # 2
# 5
# 7

exchange two variables

1
2
3
4
5
6
7
8
9
10
11
# no pythonic
a = 'hello'
b = 'world'
a,b=b,a
print(a, b) # world hello

# pythonic
a = 'hello'
b = 'world'
a,b=b,a
print(a, b) # world hello