Skip to content

Commit 18ac9fd

Browse files
author
stabla
committed
updating article, putting Toptal url
1 parent f0fef10 commit 18ac9fd

File tree

1 file changed

+62
-49
lines changed

1 file changed

+62
-49
lines changed

_posts/2020-10-30-Python-Tips-and-Tricks.md

Lines changed: 62 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,13 @@ Here's a succinct list of tips and tricks in Python.
1515

1616
Python is a powerful and simple language. There's some tricks that exists that we should use instead of reinventing the wheel.
1717

18-
<img src="https://cdn.dribbble.com/users/74401/screenshots/3022594/d-snake1.png" style=" display: block; margin: 0 auto; width: 70%;" alt="Python Tips and Tricks">
18+
<img src="https://cdn.dribbble.com/users/74401/screenshots/3022594/d-snake1.png" style=" display: block; margin: 0 auto; width: 50%;" alt="Python Tips and Tricks">
19+
20+
The goal is to let you know that exists, and if needed come back on this article to read how to do it. Let's go!
1921

2022
_________________
2123

22-
1. **Understand your scope**
24+
**Understand your scope**
2325
As you should know, scoping in Python is respecting the LEGB rule, which is abbreviation for **L**ocal, **E**nclosing, **G**lobal, Built-in
2426

2527
To make an assignment to a variable in a scope, it has to become local. Therefore, you won't be able to write a variable if it isn't global
@@ -39,7 +41,7 @@ f()
3941

4042
Note bene: using _nonlocal_ keyboard instead of _global_ would work as well.
4143

42-
2. **Enum (Python 3.4+)**
44+
**Enum (Python 3.4+)**
4345
Instead of over-using constants, you use Enum class.
4446

4547
```python
@@ -57,7 +59,7 @@ print(Color.GREEN)
5759
# Color.GREEN
5860
```
5961

60-
3. **Data Classes (Python 3.7+)**
62+
**Data Classes (Python 3.7+)**
6163

6264
DRY (Don't repeat yourself). Use data classes, Python will generate spcial methods like __init__ and __repr__ reducing repetition in your code.
6365

@@ -95,7 +97,7 @@ rectangle2 = Rectangle2("Blue, 2, 3)
9597

9698
```
9799

98-
4. **Pathlib (Python 3.4+)**
100+
**Pathlib (Python 3.4+)**
99101

100102
The module pathlib is a clean way to intereact with the file system, far better than os.path or the glob module
101103

@@ -113,7 +115,7 @@ print(path)
113115
# threads/sub/sub-sub
114116
```
115117

116-
5. **Type Hints (Python 3.5+)**
118+
**Type Hints (Python 3.5+)**
117119

118120
Typing is not necessary in Python, but it is useful for develpers after you, or you in few years. It makes your code cleaner and more understable.
119121

@@ -128,7 +130,7 @@ Typing is not necessary in Python, but it is useful for develpers after you, or
128130
return self.width * self.height
129131
```
130132

131-
6. **f-strings (3.6+)**
133+
**f-strings (3.6+)**
132134

133135
Don't use .fomrat() to print your strings, f-strings is much more convinient and easier to maintain.
134136

@@ -147,7 +149,7 @@ print(f"x = {x} and y = {y}.")
147149

148150
```
149151

150-
7. **Extendede iterable unpacking (Python 3.0+)**
152+
**Extendede iterable unpacking (Python 3.0+)**
151153

152154
Using this trick, while unpacking an iterable, you can specify a "catch-all" variable that will be assigned a list of the items not assigned to a regular variable.
153155

@@ -160,7 +162,7 @@ print(head, body, tail)
160162

161163
```
162164

163-
8. **Async IO 5Python 3.4+**
165+
**Async IO 5Python 3.4+**
164166

165167
The asyncio is a good module to write asynchronous code.
166168
```python
@@ -181,7 +183,7 @@ asyncio.un(hello())
181183
# World
182184
```
183185

184-
9. **Underrscoores in Numeric Literals (Python 3.6+)**
186+
**Underrscoores in Numeric Literals (Python 3.6+)**
185187

186188
```python
187189

@@ -192,7 +194,7 @@ printf(x, y, x == y)
192194

193195
```
194196

195-
10. **Swapping Two Variables**
197+
**Swapping Two Variables**
196198

197199
First idea when you need to swipe variables is to use a temporary variable, and blabla. But there's a better method without use a temporary variable, as such:
198200

@@ -212,7 +214,7 @@ a, b = b, a
212214
# a = 60, b = 50
213215
```
214216

215-
11. **Reversing a string**
217+
**Reversing a string**
216218

217219
In addition of swapping quickly a variable you need (not often, ok) to reverse a string, and it can be done extremely quickly.
218220

@@ -222,7 +224,7 @@ rev_string = my_string[::-1]
222224
# ROT
223225
```
224226

225-
12. **Splitting words in a line**
227+
**Splitting words in a line**
226228

227229
Of course, the old method of using .split() is a good way to do it.
228230

@@ -232,13 +234,13 @@ splitted = string.split(' ')
232234
# ['This', 'is', 'a', 'sentence']
233235
```
234236

235-
13. **List of words into a line**
237+
**List of words into a line**
236238

237239
Imagine you have ['This', 'is', 'a', 'sentence'], what to do?
238240

239241
Use the ```python "".join(string)```
240242

241-
14. **Joining two string using addition operator**
243+
**Joining two string using addition operator**
242244

243245
```python
244246
a = " I think "
@@ -247,62 +249,66 @@ print(a+b)
247249
# I think Python is great
248250
```
249251

250-
15. **More than one conditionnal operators**
252+
**More than one conditionnal operators**
251253

252254
In contrario of thers programming langage, using mathematically borned notation is accepted in Python :)
253255

254256
```python
255257
if ( 1 < a < 20):
256258
```
257259

258-
16. **Find most frequent element in a list**
260+
**Find most frequent element in a list**
259261

260262
```python
261-
list = [1, 2, 3, 2, 2, 1, 1]
262-
frequent = max(set(list), key=list.count)
263-
# 1
263+
list = [1, 2, 3, 2, 2, 1, 1]
264+
frequent = max(set(list), key=list.count)
265+
# 1
264266
```
265267

266-
17. **Count occurence of elements in a list**
268+
**Count occurence of elements in a list**
267269

268270
```python
269-
from collections import Counter
270-
print(Counter(list))
271+
from collections import Counter
272+
273+
print(Counter(list))
271274
```
272275

273-
18. **Repeating the element multiple times**
276+
**Repeating the element multiple times**
274277

275278
```python
276279
my_list = [3]
277280
my_list = my_list*5
278281
# [3, 3, 3, 3, 3]
279282
```
280283

281-
19. **Using Ternary Operator**
284+
**Using Ternary Operator**
282285

283286
```python
284287
print("Eligible") if age>20 else print("Not Eligible")
285288
# Eligible
286289
```
287290

288-
20. **Rounding with Floor and Ceil**
291+
**Rounding with Floor and Ceil**
289292

290293
```python
291294
import math
295+
292296
my_number = 18.7
293297
print(math.floor(my_number))
298+
# 18
294299
print(math.ceil(my_number))
300+
# 19
295301
```
296302

297-
21. **Function in one line**
303+
**Function in one line**
298304

299305
```python
300306
x = lambda a,b,c : a+b+c
301307
print(x(10, 20, 30))
302308
# 60
303309
```
304310

305-
22. **Apply function for each element in a list**
311+
**Apply function for each element in a list**
306312

307313
```python
308314
l = ["a", "b"]
@@ -311,7 +317,7 @@ print(list(l))
311317
# ['a', 'b']
312318
```
313319

314-
23. **Lambda functon on each element in a list**
320+
**Lambda functon on each element in a list**
315321

316322
```python
317323
l = [1, 2, 3, 4, 5]
@@ -320,7 +326,7 @@ print(list(nl))
320326
# [1, 4, 9, 16, 25]
321327
```
322328

323-
24. **Return multiple values from a function**
329+
**Return multiple values from a function**
324330
```python
325331
def function(n):
326332
return 1,2,3,4
@@ -329,7 +335,7 @@ print(a,b,c,d)
329335
# 1 2 3 4
330336
```
331337

332-
25. **Filtering the values using filter function**
338+
**Filtering the values using filter function**
333339

334340
```python
335341
def eligibility(age):
@@ -339,26 +345,27 @@ age = filter(eligibility, list_of_age)print(list(age))
339345
# [24, 27, 33, 30, 26, 25]
340346
```
341347

342-
26. **Merging two dictionnaries**
348+
**Merging two dictionnaries**
343349

344350
```python
345-
d1 = {'One':1, 'Two':2}
346-
d2 = {'Two':2, 'Three':3}
351+
d1 = {'Abra':1, 'Cadabra':2}
352+
d2 = {'Cadabra':2, 'World':3}
347353
dicti = {**d1, **d2}
348354
print(dicti)
349-
# {'One': 1, 'Two': 2, 'Three': 3}
355+
# {'Abra': 1, 'Cadabra': 2, 'World': 3}
350356
```
351357

352-
27. **Getting size of an object**
358+
**Getting size of an object**
353359

354360
```python
355361
import sys
362+
356363
a = 5
357364
print(sys.getsizeof(a))
358365
# 28
359366
```
360367

361-
28. **Two lists into diictionnary**
368+
**Two lists into dictionnary**
362369

363370
```python
364371
l1 = ["One","Two","Three"]
@@ -368,20 +375,22 @@ print(dicti)
368375
# {'Two': 2, 'One': 1, 'Three': 3}
369376
```
370377

371-
29. **Calculating execution time for a program**
378+
**Calculating execution time for a program**
372379

373380
```python
374381
import time
382+
375383
start = time.clock()
376384
for x in range(1000):
377385
pass
386+
378387
end = time.clock()
379-
total = end - start
380-
print(total)
381-
# 0.00011900000000000105
388+
389+
print(end - start)
390+
# 0.0002196058585480000
382391
```
383392

384-
30. **Removing duplicate elements in list**
393+
**Removing duplicate elements in list**
385394

386395
```python
387396
l = [1,4,1,8,2,8,4,5]
@@ -390,16 +399,20 @@ print(l)
390399
# [8, 1, 2, 4, 5]
391400
```
392401

393-
31. **Multiple assignment per variables**
402+
**Multiple assignment per variables**
394403

395404
```python
396-
a, b = 50, 60
397-
# a = 50, b = 60
398-
a, *b = 50, 60, 70
399-
# 50, [60, 70]
400-
a = b = c = 50
401-
# a = 50, b = 50, c = 50
405+
a, b = 10, 20
406+
# a = 10, b = 10
407+
a, *b = 10, 20, 30
408+
# 10, [20, 30]
409+
a = b = c = 10
410+
# a = 10, b = 10, c = 10
402411
```
403412
_________________
404413

414+
Of course, this is not a complete list of all existing Python's tricks, but it may be useful to know Python can do a lot of useful things in simple way. There is beauty in simplicity.
415+
416+
If you want to read more articles on Python, see the excellent [How to Hire a Great Python Developer](https://www.toptal.com/python#hiring-guide) from our friends at [Toptal](https://www.toptal.com/)!
417+
405418
Python is ❤️

0 commit comments

Comments
 (0)