11 Tips And Tricks To Write Better Python Code

Поделиться
HTML-код
  • Опубликовано: 14 ноя 2024

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

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

    I hope you find these tips helpful! Let me know if you have any other Python tips that improve your code :)

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

      Helpful but too many ads cut...

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

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

      @@sudhanshuranjan9 ya membership test is faster in set

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

      remarkable!

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

      Thank you!! Cheers from Chile!

  • @IlyaLisovfan
    @IlyaLisovfan 3 года назад +394

    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

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

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

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

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

      Thanks for the summary :)

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

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

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

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

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

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

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

    I love how you explain with simplicity. Great content.

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

      Thank you! Glad you like it!

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

  • @evanhagen7084
    @evanhagen7084 3 года назад +349

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

      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 👍

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

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

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

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

      Yes thanks for the tip :)

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

      i like this

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

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

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

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

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

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

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

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

  • @plumberski8854
    @plumberski8854 4 месяца назад

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

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

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

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

      yep great tip!

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

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

      @@vishnuuvardhanreddy3010 RUclips and reddit are your best friends to learn anything

    • @ИванИваныч-н3у
      @ИванИваныч-н3у 3 года назад +1

      Not worked on all versions of python, just new.

    • @ИванИваныч-н3у
      @ИванИваныч-н3у 3 года назад

      What about dict update method?

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

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

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

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

  • @etgaming6063
    @etgaming6063 Год назад +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.

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

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

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

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

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

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

    I am so glad I found this channel.

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

    First example: return [max(i, 0) for i in data]

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

      thank you for the feedback! I try to improve this on my newer videos

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

      Thank you. 😊🙏

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

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

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

    My tips:
    1.Use map instead of for
    2.Don't forget the walrus operator, just a details.
    3.Don't use func(list[0], list[1]) use func(*list)
    4.The tip 3 is also good for creating iterables in certain cases, [*list] for example
    5.Don't iterate if you want new items for the list, use list.extend()

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

      What do you think? Do you have more?

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

  • @MasterEhsan369
    @MasterEhsan369 4 месяца назад

    THANKS that was useful...

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

    The Squares example.. here's Python code:
    squares = [i*i for i in range(15)]
    print(squares)
    Here's the R code:
    x = 1:14; x^2
    Python 48 characters, 2 lines
    R 13 characters, 1 line
    Advantage: R.

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

      at 4:15 using generators:
      Python:
      my_gen = (i for i in range(10000))
      print(sum(my_gen))
      R:
      x = 1:1e4; sum(x)
      Python 52
      R 17
      Advantage: R.

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

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

  • @Arson_Oakwood
    @Arson_Oakwood 7 месяцев назад

    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.

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

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

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

    Another great video. Thanks for the amazing content.

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

      Glad you like it :)

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

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

    Superb [ ] of tips. Thank you!

  • @javohirorziqulov9644
    @javohirorziqulov9644 3 года назад +6

    only one word: amazing...

  • @HiteshKumar-178
    @HiteshKumar-178 4 года назад +3

    Really admire your work! Nice work mate

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

    Nice video! I really like that you made those slides in between the tips (gonna steal that for my future videos 😁)

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

      Thank you! Glad you like it

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

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

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

    Generators tip was quite a nice trick to know! So easy to be confounded with list generator.

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

      yep it's very handy sometimes :)

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

    2:59 you can preserve order with the help of sorted function
    example:
    my_list = [1, 2, 2, 3, 4, 5, 6, 7, 7 , 9, 8]
    sorted(set(my_list), key= lambda x: my_list.index(x))
    >>> [1, 2, 3, 4, 5, 6, 7, 9, 8]

    • @0LoneTech
      @0LoneTech Год назад +1

      Fun fact: Dictionaries are now order preserving, so you can do the old trick of using a dict as a set and keep order without sorting.
      E.g. {k:None for k in [5,2,3,2,6,5,1]}.keys()

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

    Very helpful in refactoring my brain to be more pythonic!

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

    one of the best python videos.
    Really useful

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

    Hello, Thanks for those great tips !! Does someone knows which IDE he is using ?

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

    Wonderful tips. Every single one is pretty useful.

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

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

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

    Valuable tips! Thank you very much!

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

    Excellent information,Thanks

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

    literally watched for 1:03 seconds and i love the video. I'm a beginner btw. SUBBED!

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

    bro this was super helpful. thanks for this.

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

    Thank you, this video was very helpful!

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

    you made me a better programmer with this video. Please do more series of videos like this.

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

    Very useful tips and tricks!
    Thank You

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

      glad it's helpful :)

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

    Very useful information explained in a very easy-to-understand way. Thank you for the effort.

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

      glad it was helpul!

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

    Awesome tips, thank you!

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

      Glad it's helpful!

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

    Still very relevant content, thanks for having this.

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

    thanks for the useful sharing!!!

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

    For #1, I would prefer a list comprehension: data = [0 if e < 0 else e for e in data]

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

    very helpful

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

    You are like my Python guru! Thank you Sir!

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

    Congratulations for this piece of art!!!!
    This kind of teach methodology is extremely rare.
    Thank you!

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

    Tip 1 and 2: are there any advantages in terms of performance and/or memory management? As somebody who has to work with several programming languages and switch between them on the fly, I think I'd rather keep things as uniform and generic as possible between languages rather than stick to language specific idioms just for the sake of it.

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

      You're not doing it "for the sake of it," you're making it to make your code readable to others in your team.

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

      ​@@jackgenewtf I think you missing my point about having to work with multiple programming languages, and basing your comment off an assumption that everybody else on the team is following python (or any language) specific idioms. My question was - are there any real practical (technical) benefit beyond the "we just used to do it that way" (i.e. language "idiom") and an overused "readability" argument. If people regularly work and switch between several different languages, having as uniform code structure as possible between all those languages seems like a more effective way to go, including the benefit for other team members who work with several languages as well or maybe simply not very experienced with python.
      Also, some people seem to be making a mistake by thinking that concise readable code is the same as cramming as much as possible into a single line. For example in a tip #2 of this video I would argue that a first shown method of filling a list is actually more readable and comprehensible than the second one, especially for people with limited or even no experience with python. Even for somebody not familiar with python syntax it would be more or less clear at a glance what happens in the code. Unfortunately same can not be said about a "correct" example featured in the tip.

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

      Hey! The first tipp is really useful. Because it's a common issue - at least for beginners - using len for iterations. Because they use the lenght as an index instead of length - 1.
      So this method is readable and more secure because you cant use a non existent index.
      About the list comprehetions, ... I'm also not a fan, because I had trouble in the beginning to understand these. Plus I'm not a fan of long lines.

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

    very helpful. thank you!

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

    This is a very good video. Thank you very much , keep up the good work .

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

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

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

    Best python channel in YT

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

    Thanks man, this was helpful

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

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

      It's the night owl theme. Have a look at my tutorial about my VS Code setup :)

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

    Love these Python tips

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

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

      Yes, I think it's the Night Owl theme

  • @NavinKumar-tv9hg
    @NavinKumar-tv9hg Год назад

    Wonderful. Thank you!

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

    You are Superman:) Thanks for all of sharing.

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

    Excellent video, very precise and nicely done!

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

    This is one of those channels that separate my life into pre- and post-subscription eras!

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

      this comment made my day :) glad you're here!

  • @enzopestana
    @enzopestana 4 месяца назад

    really helpful, thanks a lot

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

    Great content and background music

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

    Thank you, Subscribed to the channel

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

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

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

    Dude this is great, thanks!

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

      happy to hear this :)

  • @lakshmanans-zb5sg
    @lakshmanans-zb5sg 4 месяца назад

    combine one and two : print ([0 if value

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

    what a legend , ty very much man

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

    perfect video, good job Python Engineer

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

    super video!
    you could have included zip() function too

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

    Thanks man! Nice video!!

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

    This is very useful for me python beginner. Thank you very much sir.

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

    Thank you. Mind actually blown.

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

    Thanks for sharing this video 😊.
    But at last I can't understand that what was the final output after running the last code.

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

    Dunno why did I find you this late ?
    Please add more tips on version 3.9 too.
    Thanks.

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

    Merge dictionaries.... Woahhhhh.... Oh my God... Thank you so much... That will make my life a bit easier....

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

    Please make complete playlist like these tips of python

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

    Very nice and useful tips

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

    Great video, Thanks.

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

    This was very informative, thank you!

  • @xoca7171
    @xoca7171 3 года назад +3

    I wish I knew the get method for dicts sooner. I've been checking for the key first this whole time 😐

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

    Very useful, thanks ☺

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

    Thanks, it would help!