11 Tips And Tricks To Write Better Python Code

  Рет қаралды 596,759

Patrick Loeber

Patrick Loeber

Күн бұрын

In this video, I show 11 Tips and Tricks to Write Better Python code! I show a lot of best practices that improve your code by making your code much cleaner and more Pythonic.
Find Python jobs: pythonengineer.pallet.com
~~~~~~~~~~~~~~ GREAT PLUGINS FOR YOUR CODE EDITOR ~~~~~~~~~~~~~~
✅ Write cleaner code with Sourcery: sourcery.ai/?... *
📚 Get my FREE NumPy Handbook:
www.python-engineer.com/numpy...
📓 Notebooks available on Patreon:
/ patrickloeber
⭐ Join Our Discord : / discord
If you enjoyed this video, please subscribe to the channel!
All Tips:
1) Iterate with enumerate instead or range(len(x))
2) Use list comprehension instead of raw for loops
3) Sort complex iterables with sorted()
4) Store unique values with Sets
5) Save memory with Generators
6) Define default values in Dictionaries with .get() and .setdefault()
7) Count hashable objects with collections.Counter
8) Format strings with f-Strings (Python 3.6+)
9) Concatenate strings with .join()
10) Merge dictionaries with {**d1, **d2} (Python 3.5+)
11) Simplify if-statements with if x in list
List comprehension Tutorial: • List Comprehension in ...
~~~~~~~~~~~~~~~ CONNECT ~~~~~~~~~~~~~~~
🖥️ Website: www.python-engineer.com
🐦 Twitter - / patloeber
✉️ Newsletter - www.python-engineer.com/newsl...
📸 Instagram - / patloeber
🦾 Discord: / discord
▶️ Subscribe: / @patloeber
~~~~~~~~~~~~~~ SUPPORT ME ~~~~~~~~~~~~~~
🅿 Patreon - / patrickloeber
Music: www.bensound.com/
Python #Tips
----------------------------------------------------------------------------------------------------------
* This is a sponsored or an affiliate link. By clicking on it you will not have any additional costs, instead you will support me and my project. Thank you so much for the support! 🙏

Пікірлер: 446
@patloeber
@patloeber 3 жыл бұрын
I hope you find these tips helpful! Let me know if you have any other Python tips that improve your code :)
@uploadvoice
@uploadvoice 3 жыл бұрын
Helpful but too many ads cut...
@kingkangkan
@kingkangkan 2 жыл бұрын
Can you iterate from say idx 2 to n-4 of a list using enumerate without slicing or any extra lines of code...
@abhisheksanwal1106
@abhisheksanwal1106 2 жыл бұрын
@@sudhanshuranjan9 ya membership test is faster in set
@Princess0Reem
@Princess0Reem 2 жыл бұрын
remarkable!
@jorgemercadog
@jorgemercadog 2 жыл бұрын
Thank you!! Cheers from Chile!
@user-wg2ph7ve8c
@user-wg2ph7ve8c 2 жыл бұрын
In Python 3.9.0 or greater we can merge dictionaries using `|`: d1 = {"name": "Alex", "age": 25} d2 = {"name": "Alex", "city": "New York"} merged_dict = d1 | d2
@drygordspellweaver8761
@drygordspellweaver8761 2 жыл бұрын
I like this as it stays true to Pipe symbol
@billw8dsx939
@billw8dsx939 Жыл бұрын
you rock
@CryptoIgnition
@CryptoIgnition Жыл бұрын
And print(merged_dict == d1 | d2) will print out true
@flames9310
@flames9310 Жыл бұрын
This syntax is way simpler.
@albo5194
@albo5194 Жыл бұрын
Is there an easy (and fast for large dictionaries) way to merge dictionaries in a way, that it includes every value of both dicts with the same key? for example, if d2 would include "name": "Luca" instead of "Alex", i would like the merged output to be like: {"name": ["Alex", "Luca"], "age": 25, "city": "New York"}
@FailedSquare
@FailedSquare 3 жыл бұрын
0:20 Iterate with Enumerate x For Loops with If 1:02 List Comprehension x For Loops 1:51 Sort iterables with sorted() 3:00 Unique values with Sets 3:37 Generators replacement for Lists 4:58 default values for dictionary keys 6:06 Count objects with collections.Counter 7:39 f-Strings > str.format() 8:20 Build up strings with .join() 9:27 merge dictionaries - This feature is updated again in 3.9 using | 10:00 simplify if statements
@patloeber
@patloeber 3 жыл бұрын
Thanks for the summary :)
@yt-sh
@yt-sh 2 жыл бұрын
@@patloeber you made this in 11 min, I see what u did there
@DavidTangye
@DavidTangye 2 жыл бұрын
@@patloeber This is a very nice video for quick reference on these coding best practices. Can you please copy this list of times to the video Description for future reference. That makes the vid hugely helpful for in future.
@jordangl1
@jordangl1 2 жыл бұрын
Your videos are by far the most concise and easiest to assimilate compared to every other YT Python teacher (to me). Thanks for taking the time. Good stuff
@Daniel-um9ye
@Daniel-um9ye Жыл бұрын
Superb content. I am a C++ programmer, but since 2019 have been dabbling with python. Being pythonic is actually what I look for as of now. Thanks.
@evanhagen7084
@evanhagen7084 2 жыл бұрын
On the last tip it would be much faster to use a set instead of a list. Sets have constant lookup time but lists have O(n) lookup time.
@sshishov
@sshishov 2 жыл бұрын
To convert list into set you need to execute O(n) operation.
@evanhagen7084
@evanhagen7084 2 жыл бұрын
@@sshishov my point is you shouldn't even create a list in the first place. You should create a set to begin with
@sshishov
@sshishov 2 жыл бұрын
Agree, but sometimes lists are needed if you want to keep duplicates or you want to keep items in inserted order.
@andraspongracz5996
@andraspongracz5996 2 жыл бұрын
@@sshishov True, but if you want to check membership, say, n times, than its O(n) vs. O(n**2). It depends on the problem which data structure is better, as your second comment shows. But if you are only worried about runtime, then @Evan Hagen is correct: you basically cannot lose by using a set (I mean even if you have to convert first), because if you run it once, it is the same runtime, but if you do it many times, then set is the better choice.
@sshishov
@sshishov 2 жыл бұрын
@@andraspongracz5996 agree 👍
@manuelmanolo7099
@manuelmanolo7099 2 жыл бұрын
I thought this would be something that would go way over my head but, as some that recently started learning python, this was really valuable!
@saurabhjain507
@saurabhjain507 3 жыл бұрын
I love how you explain with simplicity. Great content.
@patloeber
@patloeber 3 жыл бұрын
Thank you! Glad you like it!
@eminm6383
@eminm6383 2 жыл бұрын
I almost don't know any python, but I was able to comprehend 80% of the content. Amazing simple explanation. Thanks.
@Kinos141
@Kinos141 2 жыл бұрын
Finally, how to do strings properly. I love using something like that in c#, and I'm glad it's on other languages like python.
@thebuggser2752
@thebuggser2752 2 жыл бұрын
Great collection of useful tips, presented very clearly and concisely. Thanks!!
@schedarr
@schedarr 2 жыл бұрын
That is absolutely golden video. Extremaly useful tricks that will make your life way much easier. I've already used 10 out of 11 but still it's nice refresher.
@patloeber
@patloeber 2 жыл бұрын
Great to hear!
@davidvanleeuwen3274
@davidvanleeuwen3274 2 жыл бұрын
Thanks a lot! The first minute already helps a lot.
@TheSuperUser
@TheSuperUser 3 жыл бұрын
Great video. Please make more of these quick tips for comparisons of "beginner" python code vs experienced developer idioms
@patloeber
@patloeber 3 жыл бұрын
Thanks :)
@octobotdev
@octobotdev Жыл бұрын
Thanks for the tips, always great to listen to fellow Python devs!
@RicardoAmaralAndrade
@RicardoAmaralAndrade 2 жыл бұрын
Simply wonderful! Subscribed in the first 2 minutes! Python is the greatest modern language, and these tips are gold!
@patloeber
@patloeber 2 жыл бұрын
Thank you so much!
@rushi7312
@rushi7312 2 жыл бұрын
I'm a beginner -ish and knew about half to 2/3rd, but also learned a few good tricks :) Thanks
@vitalimueller6209
@vitalimueller6209 3 жыл бұрын
Nr.3 you can also do: from operator import itemgetter sorted_data = sorted(data, key=itemgetter('age'))
@patloeber
@patloeber 3 жыл бұрын
Yes thanks for the tip :)
@Mdroudian
@Mdroudian 2 жыл бұрын
i like this
@ekkyarmandi
@ekkyarmandi 2 жыл бұрын
Nice tips. It speedup my code writing. Thanks, man.
@alyssonmachado1254
@alyssonmachado1254 2 жыл бұрын
Valuable tips! Thank you very much!
@mywebuniversity
@mywebuniversity Жыл бұрын
Excellent video, very precise and nicely done!
@davidtalturejman9185
@davidtalturejman9185 8 ай бұрын
Thanks man! Nice video!!
@chakkarapaniv
@chakkarapaniv 3 жыл бұрын
Hey, Excellent videos. The style is amazing! and more informative!. I am following you.
@patloeber
@patloeber 3 жыл бұрын
Great, thank you!
@jmsl2027
@jmsl2027 3 жыл бұрын
This was very informative, thank you!
@rutanshudesai
@rutanshudesai Жыл бұрын
amazing tips, very very valuable. thank you for sharing.
@victorsuarez4333
@victorsuarez4333 2 жыл бұрын
Thank you, this video was very helpful!
@MrGustavCR
@MrGustavCR 3 жыл бұрын
Another great video. Thanks for the amazing content.
@patloeber
@patloeber 3 жыл бұрын
Glad you like it :)
@fahnub
@fahnub 2 жыл бұрын
bro this was super helpful. thanks for this.
@adamdeuxieme
@adamdeuxieme Жыл бұрын
Thanks for these good tips !
@akashgillella
@akashgillella 2 жыл бұрын
Wonderful tips. Every single one is pretty useful.
@wintur2856
@wintur2856 3 ай бұрын
Thanks for these tips! It's hard finding content outside beginner courses.
@LuisGL90
@LuisGL90 Жыл бұрын
Nice tips! Thankyou so much!
@NavinKumar-tv9hg
@NavinKumar-tv9hg 8 ай бұрын
Wonderful. Thank you!
@abdallahsalim4759
@abdallahsalim4759 2 жыл бұрын
Thanks man, this was helpful
@manojm9084
@manojm9084 2 жыл бұрын
This is a very good video. Thank you very much , keep up the good work .
@HKHforpeace
@HKHforpeace 3 жыл бұрын
Really admire your work! Nice work mate
@patloeber
@patloeber 3 жыл бұрын
Thank you!
@AmitabhSuman
@AmitabhSuman Жыл бұрын
Really useful tricks! Thanks for sharing.
@gauravrajput8109
@gauravrajput8109 Жыл бұрын
I am so glad I found this channel.
@latt.qcd9221
@latt.qcd9221 2 жыл бұрын
The idea of list comprehensions was new to me, but I was curious if there was an option for dictionary comprehensions and, sure enough, there is! Was able to clean up a lot of my dictionary for loops. Thanks!
@janusztarnowski115
@janusztarnowski115 Жыл бұрын
and what you think about it ?kzbin.info/www/bejne/rpXQmp2fo9eeY9k
@faizalimuhammadzoda4731
@faizalimuhammadzoda4731 3 жыл бұрын
Very useful information explained in a very easy-to-understand way. Thank you for the effort.
@patloeber
@patloeber 2 жыл бұрын
glad it was helpul!
@PhuongVu-jv9eg
@PhuongVu-jv9eg 2 жыл бұрын
Thank you very much! Keep up with the good work!
@patloeber
@patloeber 2 жыл бұрын
Thanks, will do!
@Zephyr-tg9hu
@Zephyr-tg9hu 3 жыл бұрын
Awesome tips, thank you!
@patloeber
@patloeber 3 жыл бұрын
Glad it's helpful!
@nebular-nerd
@nebular-nerd Жыл бұрын
Some interesting tips, I'm just going through a reformat of a new script and this should help tidy and speed some operations.
@venkatesanr9455
@venkatesanr9455 3 жыл бұрын
Expecting some series and by the way, good explanation with informative content, it helps a lot
@patloeber
@patloeber 3 жыл бұрын
Thanks!
@faithinverity8523
@faithinverity8523 2 жыл бұрын
Superb [ ] of tips. Thank you!
@AladdinPersson
@AladdinPersson 3 жыл бұрын
Nice video! I really like that you made those slides in between the tips (gonna steal that for my future videos 😁)
@patloeber
@patloeber 3 жыл бұрын
Thank you! Glad you like it
@PaulTheEldritchCat
@PaulTheEldritchCat 2 жыл бұрын
Nice tips, I'll save the video for later. Thanks!
@jth5726
@jth5726 2 жыл бұрын
dude, I've been doing a programming course 12 weeks, I feel like f-strings are something we should have been taught immediately, why am I only learning it through you
@datastako156
@datastako156 Жыл бұрын
very helpful. thank you!
@vaggo9611
@vaggo9611 3 жыл бұрын
perfect video, good job Python Engineer
@patloeber
@patloeber 3 жыл бұрын
Thanks so much!
@alankritverma1839
@alankritverma1839 3 ай бұрын
one of the best python videos. Really useful
@jomelsanpedro7271
@jomelsanpedro7271 2 жыл бұрын
thank you so much. keep it up you're the best.
@patloeber
@patloeber 2 жыл бұрын
thank you!
@YouAreNotFree1
@YouAreNotFree1 2 жыл бұрын
First example: return [max(i, 0) for i in data]
@GaelGendre
@GaelGendre 2 жыл бұрын
Dude this is great, thanks!
@patloeber
@patloeber 2 жыл бұрын
happy to hear this :)
@_Amilio_
@_Amilio_ 2 жыл бұрын
Love these Python tips
@akira_asahi
@akira_asahi Жыл бұрын
Thank you for the video. I am grateful for your time and contribution. Kind regards, Akira.
@shababe2243
@shababe2243 Жыл бұрын
Excellent information,Thanks
@akshitstenaa
@akshitstenaa 2 жыл бұрын
I am your fan now , thx a ton mate for all these tips.
@patloeber
@patloeber 2 жыл бұрын
Awesome, thank you!
@akshitstenaa
@akshitstenaa 2 жыл бұрын
Please try adding videos on Scarpping, ML & analytics . 🙂
@prashanthreddy1924
@prashanthreddy1924 2 жыл бұрын
you made me a better programmer with this video. Please do more series of videos like this.
@patloeber
@patloeber 2 жыл бұрын
glad to hear this!
@mostafasadeq3153
@mostafasadeq3153 Жыл бұрын
what a legend , ty very much man
@zacky7862
@zacky7862 2 жыл бұрын
This is great. I'm always looking on better coding style. Could you tell which vs code theme that you are using? Thanks
@patloeber
@patloeber 2 жыл бұрын
Yes, I think it's the Night Owl theme
3 жыл бұрын
Hey dude. Thanks for this video, it helped me a lot in my studies! What's the theme you're using? I found it really cool and couldn't find it on the marketplace
@patloeber
@patloeber 3 жыл бұрын
It's the night owl theme. Have a look at my tutorial about my VS Code setup :)
@gudguy1a
@gudguy1a 6 ай бұрын
Still very relevant content, thanks for having this.
@knowledgedaily1173
@knowledgedaily1173 2 жыл бұрын
This is one of the best python related videos I have seen.
@patloeber
@patloeber 2 жыл бұрын
thanks a lot!
@mohamedmzoughi8234
@mohamedmzoughi8234 2 жыл бұрын
Very informative great job
@changwei-zhe9406
@changwei-zhe9406 2 жыл бұрын
thanks for the useful sharing!!!
@patloeber
@patloeber 2 жыл бұрын
glad you like it!
@tincustefanlucian7495
@tincustefanlucian7495 2 жыл бұрын
Generators tip was quite a nice trick to know! So easy to be confounded with list generator.
@patloeber
@patloeber 2 жыл бұрын
yep it's very handy sometimes :)
@manuelpardall8688
@manuelpardall8688 2 жыл бұрын
Very useful tips and tricks! Thank You
@patloeber
@patloeber 2 жыл бұрын
glad it's helpful :)
@petelogiudice8202
@petelogiudice8202 2 жыл бұрын
Very helpful in refactoring my brain to be more pythonic!
@nates3361
@nates3361 2 жыл бұрын
You are like my Python guru! Thank you Sir!
@patloeber
@patloeber 2 жыл бұрын
glad you like it!
@dineshbawage1297
@dineshbawage1297 3 жыл бұрын
Very nice and informative. the videos u made for python are really interesting and enjoyable. Would you create some for the oops concepts and also any video regarding pytest frameworks. Thanks a lot and keep posting
@patloeber
@patloeber 3 жыл бұрын
Thanks! Yes I will add those topics to my list :)
@mariovega6282
@mariovega6282 2 жыл бұрын
Most excellent video!
@diegoftorrent
@diegoftorrent 3 жыл бұрын
Congratulations for this piece of art!!!! This kind of teach methodology is extremely rare. Thank you!
@janusztarnowski115
@janusztarnowski115 2 жыл бұрын
what you think about this ? kzbin.info/www/bejne/eojRZmB7n52FY68
@srimanthmahadev8272
@srimanthmahadev8272 2 жыл бұрын
An alternative of TIP 10: if you have two dictionaries you can join them using | operator. d1={'one' : 1, 'two':2} d2={'three':3} d3=d1|d2 print(d3) output: {'one': 1, 'two': 2, 'three': 3}
@patloeber
@patloeber 2 жыл бұрын
yep great tip!
@vishnuuvardhanreddy3010
@vishnuuvardhanreddy3010 2 жыл бұрын
Bro i am new to python I am very much interested to learn python please give me suggestion to develop my python basics to reach up to a professional level
@notbme2731
@notbme2731 2 жыл бұрын
@@vishnuuvardhanreddy3010 KZbin and reddit are your best friends to learn anything
@user-zk3uo3ti6f
@user-zk3uo3ti6f 2 жыл бұрын
Not worked on all versions of python, just new.
@user-zk3uo3ti6f
@user-zk3uo3ti6f 2 жыл бұрын
What about dict update method?
@shashishekhar----
@shashishekhar---- 2 жыл бұрын
very informative video brother 👍
@arsonoakwood7938
@arsonoakwood7938 Ай бұрын
I'm amazed at how there are beginner programmers, who never read basic tutorial in official documentation, and then watch similar videos, thinking they are learning advanced concepts.
@misaelpereira9679
@misaelpereira9679 Жыл бұрын
Awesome tips!
@gomathikreddy350
@gomathikreddy350 2 жыл бұрын
Great content. Thank you for sharing ur knowledge. It'll help if the font sizes are larger for screen casts. I watch ur videos on an old android phone. 😐
@patloeber
@patloeber 2 жыл бұрын
thank you for the feedback! I try to improve this on my newer videos
@gomathikreddy350
@gomathikreddy350 2 жыл бұрын
Thank you. 😊🙏
@onurkoc6869
@onurkoc6869 2 жыл бұрын
You are Superman:) Thanks for all of sharing.
@TejasBangera
@TejasBangera 3 жыл бұрын
Thank you, Subscribed to the channel
@patloeber
@patloeber 3 жыл бұрын
Thanks!
@pouyan74
@pouyan74 2 жыл бұрын
This is one of those channels that separate my life into pre- and post-subscription eras!
@patloeber
@patloeber 2 жыл бұрын
this comment made my day :) glad you're here!
@krupaneshkrishnan9284
@krupaneshkrishnan9284 2 жыл бұрын
Great video, Thanks.
@castlecodersltd
@castlecodersltd Жыл бұрын
Very useful, thanks ☺
@marco.nascimento
@marco.nascimento 2 жыл бұрын
Great tips!!
@patloeber
@patloeber 2 жыл бұрын
thank you!
@etgaming6063
@etgaming6063 8 ай бұрын
If you aren't speeding up your videos during your scripting then you are a REALLY FAST typer, like holy crap. IDK how you can type those lists in under a second, that is crazy to me.
@kitgary
@kitgary 3 жыл бұрын
Very useful! More advanced topics please!
@patloeber
@patloeber 3 жыл бұрын
Thanks! I’ll try :)
@leesweets4110
@leesweets4110 Жыл бұрын
Generators and dictionary merger were new to me and I can see being very useful. Are generators more costly in terms of time efficiency? Seems to me that calling it multiple times is less efficient than having a precomputed list.
@ajaysurya9075
@ajaysurya9075 2 жыл бұрын
Thanks for sharing this video 😊. But at last I can't understand that what was the final output after running the last code.
@travelchimps6637
@travelchimps6637 2 ай бұрын
Great content and background music
@jorgeluismongeblanco6933
@jorgeluismongeblanco6933 Жыл бұрын
For #1, I would prefer a list comprehension: data = [0 if e < 0 else e for e in data]
@mrsingh5351
@mrsingh5351 2 жыл бұрын
super video! you could have included zip() function too
@cktv3
@cktv3 3 жыл бұрын
You did a good job, thanks
@patloeber
@patloeber 3 жыл бұрын
thanks!
@p0ngzzznea780
@p0ngzzznea780 2 жыл бұрын
This is very useful for me python beginner. Thank you very much sir.
@patloeber
@patloeber 2 жыл бұрын
Glad to hear that
@mmxo2631
@mmxo2631 2 жыл бұрын
literally watched for 1:03 seconds and i love the video. I'm a beginner btw. SUBBED!
@eugenenazirov
@eugenenazirov Жыл бұрын
Hello from Kazakhstan! Can you explain how the sorted() works inside? And what's the complexity of the algorithm of sorting complex iterables using sorted(iterable, key=) ?
@peteralexander4892
@peteralexander4892 3 жыл бұрын
Excellent, thank you
@patloeber
@patloeber 3 жыл бұрын
Glad you like it!
@tigrayrimey6418
@tigrayrimey6418 3 жыл бұрын
Great point Sir! Do you have any python implementation code for the passive-aggressive algorithm from scratch for Multiclass classification?
@patloeber
@patloeber 2 жыл бұрын
hmm not yet...
@anthonycokayne7453
@anthonycokayne7453 2 жыл бұрын
Great tips 🙂 thanks
@swannschilling474
@swannschilling474 2 жыл бұрын
This is great!! 😊
@patloeber
@patloeber 2 жыл бұрын
thanks :)
@zacky7862
@zacky7862 2 жыл бұрын
Could you please tell how to safely count or check the if the generators items are empty?
10 Python Shortcuts You Need To Know
27:27
Tech With Tim
Рет қаралды 289 М.
5 Tips To Write Better Python Functions
15:59
Indently
Рет қаралды 64 М.
蜘蛛侠这操作也太坏了吧#蜘蛛侠#超人#超凡蜘蛛
00:47
超凡蜘蛛
Рет қаралды 45 МЛН
Қайрат Нұртас & ИРИНА КАЙРАТОВНА - Түн
03:41
RAKHMONOV ENTERTAINMENT
Рет қаралды 1,8 МЛН
Glow Stick Secret 😱 #shorts
00:37
Mr DegrEE
Рет қаралды 84 МЛН
Surprise Gifts #couplegoals
00:21
Jay & Sharon
Рет қаралды 27 МЛН
How Senior Programmers ACTUALLY Write Code
13:37
Healthy Software Developer
Рет қаралды 1,2 МЛН
Python dataclasses will save you HOURS, also featuring attrs
8:50
50 Python Tips and Tricks for Beginners
43:22
Caleb Curry
Рет қаралды 63 М.
Quick Python Refactoring Tips
5:07
Patrick Loeber
Рет қаралды 108 М.
5 Good Python Habits
17:35
Indently
Рет қаралды 283 М.
10 Python Basics You Should Know!
10:08
Patrick Loeber
Рет қаралды 78 М.
3 PYTHON AUTOMATION PROJECTS FOR BEGINNERS
17:00
Internet Made Coder
Рет қаралды 1,4 МЛН
8 Python Coding Tips - From The Google Python Style Guide
17:12
ArjanCodes
Рет қаралды 152 М.
Python's 5 Worst Features
19:44
Indently
Рет қаралды 57 М.
Write Python Code Properly!
25:46
Tech With Tim
Рет қаралды 139 М.
蜘蛛侠这操作也太坏了吧#蜘蛛侠#超人#超凡蜘蛛
00:47
超凡蜘蛛
Рет қаралды 45 МЛН