11 Tips And Tricks To Write Better Python Code

Поделиться
HTML-код
  • Опубликовано: 10 июл 2024
  • 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! 🙏

Комментарии • 451

  • @patloeber
    @patloeber  4 года назад +136

    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...

    • @kingkhann9
      @kingkhann9 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 года назад +1

      @@sudhanshuranjan9 ya membership test is faster in set

    • @Princess0Reem
      @Princess0Reem 2 года назад +1

      remarkable!

    • @jorgemercadog
      @jorgemercadog 2 года назад

      Thank you!! Cheers from Chile!

  • @user-wg2ph7ve8c
    @user-wg2ph7ve8c 2 года назад +381

    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 года назад +10

      I like this as it stays true to Pipe symbol

    • @billw8dsx939
      @billw8dsx939 2 года назад +1

      you rock

    • @CryptoIgnition
      @CryptoIgnition Год назад +5

      And
      print(merged_dict == d1 | d2)
      will print out true

    • @flames9310
      @flames9310 Год назад +1

      This syntax is way simpler.

    • @albo5194
      @albo5194 Год назад +1

      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 года назад +262

    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 года назад +8

      Thanks for the summary :)

    • @yt-sh
      @yt-sh 2 года назад +4

      @@patloeber you made this in 11 min, I see what u did there

    • @DavidTangye
      @DavidTangye 2 года назад +6

      @@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 года назад +5

    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 Год назад +9

    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.

  • @thebuggser2752
    @thebuggser2752 2 года назад +5

    Great collection of useful tips, presented very clearly and concisely. Thanks!!

  • @manuelmanolo7099
    @manuelmanolo7099 2 года назад +9

    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!

  • @evanhagen7084
    @evanhagen7084 2 года назад +343

    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 года назад +35

      To convert list into set you need to execute O(n) operation.

    • @evanhagen7084
      @evanhagen7084 2 года назад +46

      @@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 года назад +46

      Agree, but sometimes lists are needed if you want to keep duplicates or you want to keep items in inserted order.

    • @andraspongracz5996
      @andraspongracz5996 2 года назад +13

      @@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 года назад +5

      @@andraspongracz5996 agree 👍

  • @davidtalturejman9185
    @davidtalturejman9185 10 месяцев назад

    Thanks man! Nice video!!

  • @LuisGL90
    @LuisGL90 Год назад

    Nice tips! Thankyou so much!

  • @adamdeuxieme
    @adamdeuxieme Год назад

    Thanks for these good tips !

  • @NavinKumar-tv9hg
    @NavinKumar-tv9hg 10 месяцев назад

    Wonderful. Thank you!

  • @datastako156
    @datastako156 Год назад

    very helpful. thank you!

  • @davidvanleeuwen3274
    @davidvanleeuwen3274 2 года назад +1

    Thanks a lot! The first minute already helps a lot.

  • @shababe2243
    @shababe2243 Год назад

    Excellent information,Thanks

  • @eminm6383
    @eminm6383 2 года назад +3

    I almost don't know any python, but I was able to comprehend 80% of the content. Amazing simple explanation. Thanks.

  • @Kinos141
    @Kinos141 2 года назад +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.

  • @plumberski8854
    @plumberski8854 8 дней назад

    Clear tips, like how you explain them, are simple and clear!

  • @schedarr
    @schedarr 3 года назад +9

    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.

  • @ekkyarmandi
    @ekkyarmandi 2 года назад

    Nice tips. It speedup my code writing. Thanks, man.

  • @enzopestana
    @enzopestana 16 дней назад

    really helpful, thanks a lot

  • @saurabhjain507
    @saurabhjain507 4 года назад +24

    I love how you explain with simplicity. Great content.

    • @patloeber
      @patloeber  4 года назад +8

      Thank you! Glad you like it!

  • @krupaneshkrishnan9284
    @krupaneshkrishnan9284 2 года назад

    Great video, Thanks.

  • @octobotdev
    @octobotdev Год назад

    Thanks for the tips, always great to listen to fellow Python devs!

  • @mariovega6282
    @mariovega6282 2 года назад

    Most excellent video!

  • @mywebuniversity
    @mywebuniversity Год назад

    Excellent video, very precise and nicely done!

  • @castlecodersltd
    @castlecodersltd Год назад

    Very useful, thanks ☺

  • @RicardoAmaralAndrade
    @RicardoAmaralAndrade 2 года назад +2

    Simply wonderful! Subscribed in the first 2 minutes! Python is the greatest modern language, and these tips are gold!

  • @rutanshudesai
    @rutanshudesai Год назад

    amazing tips, very very valuable. thank you for sharing.

  • @alyssonmachado1254
    @alyssonmachado1254 2 года назад

    Valuable tips! Thank you very much!

  • @fahnub
    @fahnub 2 года назад

    bro this was super helpful. thanks for this.

  • @misaelpereira9679
    @misaelpereira9679 2 года назад

    Awesome tips!

  • @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.

  • @AmitabhSuman
    @AmitabhSuman Год назад

    Really useful tricks! Thanks for sharing.

  • @rithirongk
    @rithirongk 2 года назад

    awesome! thx a lot.

  • @victorsuarez4333
    @victorsuarez4333 2 года назад

    Thank you, this video was very helpful!

  • @mostafasadeq3153
    @mostafasadeq3153 Год назад

    what a legend , ty very much man

  • @akashgillella
    @akashgillella 2 года назад

    Wonderful tips. Every single one is pretty useful.

  • @faithinverity8523
    @faithinverity8523 2 года назад

    Superb [ ] of tips. Thank you!

  • @TheSuperUser
    @TheSuperUser 3 года назад +39

    Great video. Please make more of these quick tips for comparisons of "beginner" python code vs experienced developer idioms

  • @alankritverma1839
    @alankritverma1839 5 месяцев назад

    one of the best python videos.
    Really useful

  • @whonayem01
    @whonayem01 2 года назад

    Thanks, it would help!

  • @MasterEhsan369
    @MasterEhsan369 9 дней назад

    THANKS that was useful...

  • @onurkoc6869
    @onurkoc6869 2 года назад

    You are Superman:) Thanks for all of sharing.

  • @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 .

  • @PaulTheEldritchCat
    @PaulTheEldritchCat 2 года назад

    Nice tips, I'll save the video for later. Thanks!

  • @marco.nascimento
    @marco.nascimento 2 года назад

    Great tips!!

  • @mykyta1235
    @mykyta1235 Год назад

    such a great content. Thank you

  • @akira_asahi
    @akira_asahi 2 года назад

    Thank you for the video. I am grateful for your time and contribution. Kind regards, Akira.

  • @wintur2856
    @wintur2856 5 месяцев назад

    Thanks for these tips! It's hard finding content outside beginner courses.

  • @chakkarapaniv
    @chakkarapaniv 3 года назад +1

    Hey, Excellent videos. The style is amazing! and more informative!. I am following you.

  • @namanthacker
    @namanthacker 3 месяца назад

    Very nice and useful tips

  • @Zephyr-tg9hu
    @Zephyr-tg9hu 3 года назад +1

    Awesome tips, thank you!

    • @patloeber
      @patloeber  3 года назад +1

      Glad it's helpful!

  • @PhuongVu-jv9eg
    @PhuongVu-jv9eg 3 года назад

    Thank you very much! Keep up with the good work!

  • @gudguy1a
    @gudguy1a 8 месяцев назад

    Still very relevant content, thanks for having this.

  • @shashishekhar----
    @shashishekhar---- 2 года назад

    very informative video brother 👍

  • @rabindrareddy6164
    @rabindrareddy6164 Год назад

    great lesson sir

  • @mohamedmzoughi8234
    @mohamedmzoughi8234 2 года назад

    Very informative great job

  • @farhangjaryani8237
    @farhangjaryani8237 2 года назад

    Thanks for share

  • @_Amilio_
    @_Amilio_ 3 года назад +1

    Love these Python tips

  • @rushi7312
    @rushi7312 2 года назад +2

    I'm a beginner -ish and knew about half to 2/3rd, but also learned a few good tricks :)
    Thanks

  • @terrisquire1940
    @terrisquire1940 2 года назад

    Thank you very much!

  • @TheSuperi0rX
    @TheSuperi0rX Год назад

    Very very good !

  • @anthonycokayne7453
    @anthonycokayne7453 2 года назад

    Great tips 🙂 thanks

  • @travelchimps6637
    @travelchimps6637 5 месяцев назад

    Great content and background music

  • @jomelsanpedro7271
    @jomelsanpedro7271 2 года назад

    thank you so much. keep it up you're the best.

  • @changwei-zhe9406
    @changwei-zhe9406 2 года назад

    thanks for the useful sharing!!!

  • @gauravrajput8109
    @gauravrajput8109 2 года назад

    I am so glad I found this channel.

  • @manuelpardall8688
    @manuelpardall8688 2 года назад

    Very useful tips and tricks!
    Thank You

    • @patloeber
      @patloeber  2 года назад +1

      glad it's helpful :)

  • @luckyboy-ih5hd
    @luckyboy-ih5hd 2 года назад +1

    very helpful

  • @petelogiudice8202
    @petelogiudice8202 2 года назад

    Very helpful in refactoring my brain to be more pythonic!

  • @jmsl2027
    @jmsl2027 3 года назад +1

    This was very informative, thank you!

  • @peteralexander4892
    @peteralexander4892 4 года назад

    Excellent, thank you

  • @GaelGendre
    @GaelGendre 2 года назад

    Dude this is great, thanks!

    • @patloeber
      @patloeber  2 года назад

      happy to hear this :)

  • @adjans539
    @adjans539 3 года назад

    I subscribed thanks!

    • @patloeber
      @patloeber  3 года назад +1

      thanks for subscribing!

  • @runggp
    @runggp 2 года назад

    excellent!

  • @user-wr4yl7tx3w
    @user-wr4yl7tx3w 2 года назад

    Great video

  • @vitalimueller6209
    @vitalimueller6209 3 года назад +24

    Nr.3 you can also do:
    from operator import itemgetter
    sorted_data = sorted(data, key=itemgetter('age'))

    • @patloeber
      @patloeber  3 года назад +4

      Yes thanks for the tip :)

    • @Mdroudian
      @Mdroudian 2 года назад

      i like this

  • @sig7813
    @sig7813 2 года назад

    Very cool. Learn from you a lot

  • @latt.qcd9221
    @latt.qcd9221 3 года назад +1

    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 ?ruclips.net/video/xdmijinrk-w/видео.html

  • @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 :)

  • @manajitdas7619
    @manajitdas7619 2 года назад

    Thank you.

  • @vaggo9611
    @vaggo9611 3 года назад +1

    perfect video, good job Python Engineer

  • @TejasBangera
    @TejasBangera 4 года назад +1

    Thank you, Subscribed to the channel

  • @The1enzo2
    @The1enzo2 2 года назад

    great video!

  • @swannschilling474
    @swannschilling474 2 года назад

    This is great!! 😊

  • @sanjeeth123
    @sanjeeth123 3 года назад

    brilliant tips

  • @maxfondle6793
    @maxfondle6793 2 года назад

    Thank you. Mind actually blown.

  • @SACHINKUMAR-px8kq
    @SACHINKUMAR-px8kq Год назад

    Thanks Sir

  • @perceptron5983
    @perceptron5983 3 года назад

    Great suggestions.

  • @jonathanmoore5619
    @jonathanmoore5619 Год назад

    Thank you

  • @MrGustavCR
    @MrGustavCR 4 года назад +8

    Another great video. Thanks for the amazing content.

    • @patloeber
      @patloeber  4 года назад +2

      Glad you like it :)

  • @meFisttoU
    @meFisttoU 2 года назад

    awesome and very helpful video

    • @patloeber
      @patloeber  2 года назад

      Glad it was helpful!

  • @cktv3
    @cktv3 3 года назад

    You did a good job, thanks

  • @saiprasadchintakindi7596
    @saiprasadchintakindi7596 2 года назад

    Great one 👍

  • @etgaming6063
    @etgaming6063 10 месяцев назад +1

    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.

  • @jth5726
    @jth5726 2 года назад +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

  • @akshitstenaa
    @akshitstenaa 3 года назад

    I am your fan now , thx a ton mate for all these tips.

    • @patloeber
      @patloeber  3 года назад +1

      Awesome, thank you!

    • @akshitstenaa
      @akshitstenaa 3 года назад

      Please try adding videos on Scarpping, ML & analytics . 🙂

  • @knowledgedaily1173
    @knowledgedaily1173 2 года назад

    This is one of the best python related videos I have seen.