11 Tips And Tricks To Write Better Python Code

Поділитися
Вставка
  • Опубліковано 29 вер 2024

КОМЕНТАРІ • 452

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

  • @IlyaLisovfan
    @IlyaLisovfan 2 роки тому +390

    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 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"}

  • @MarioVegaTOAO
    @MarioVegaTOAO 2 роки тому

    Most excellent video!

  • @emilioschmidt2106
    @emilioschmidt2106 3 роки тому

    Why does the .join method not accept generators? Wouldn't that be a perfect use case as you only need the values of the list one at a time

    • @patloeber
      @patloeber  3 роки тому

      yeah it's only implemented for strings, but you could implement your own join method for generators

  • @FailedSquare
    @FailedSquare 3 роки тому +264

    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.

  • @evanhagen7084
    @evanhagen7084 2 роки тому +347

    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 👍

  • @MisterFanwank
    @MisterFanwank 2 роки тому +1

    Tip #1: Use a real programming language. No, I don't mean Haskell, Rust, Dart, or whatever other silly memelangs the mouth breathing pseuds are championing this week. Use a language that gives you a real memcpy and doesn't punish you for stupid reasons if you use it.

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

  • @TheSuperUser
    @TheSuperUser 3 роки тому +39

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

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

  • @vitalimueller6209
    @vitalimueller6209 3 роки тому +24

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

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

  • @YouAreNotFree1
    @YouAreNotFree1 3 роки тому +2

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

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

  • @DisSsha
    @DisSsha 2 роки тому +2

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

  • @saurabhjain507
    @saurabhjain507 4 роки тому +24

    I love how you explain with simplicity. Great content.

    • @patloeber
      @patloeber  4 роки тому +8

      Thank you! Glad you like it!

  • @azsxcvbnhjks
    @azsxcvbnhjks 3 роки тому +1

    the first tips give error if you try it.
    'int' object does not support item assignment

  • @xoca7171
    @xoca7171 2 роки тому +3

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

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

  • @javohirorziqulov9644
    @javohirorziqulov9644 3 роки тому +6

    only one word: amazing...

  • @thebuggser2752
    @thebuggser2752 2 роки тому +5

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

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

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

  • @MrGustavCR
    @MrGustavCR 4 роки тому +8

    Another great video. Thanks for the amazing content.

  • @rushi7312
    @rushi7312 2 роки тому +2

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

  • @Kinos141
    @Kinos141 2 роки тому +1

    I noticed that merge dictionaries doesn't merge into a new line, but more over writes the old on. I changed the name in the d2, and it overwrote the name in d1.
    I thought it would just create a new name in the dict.
    Is this the intended behavior?

  • @josuemonteiro6017
    @josuemonteiro6017 5 місяців тому

    man... idk if i did it right.. but seems like the first improvment dont works with a lot of data... look: @clock
    def test_1():
    for i in range(len(dados)):
    if i % 2 == 0:
    dados[i] = 0
    @clock
    def test_1_improved():
    for index, i in enumerate(dados):
    if i % 2 == 0:
    dados[index] = 0

    test_1()
    test_1_improved()
    where data is a list of all the number from 1 to 10000. look the output:
    test_1 executou em 0.00046789998305030167 segundos
    test_1_improved executou em 0.000614999997196719 segundos
    test_1_improved did in more time!! what shold i do? thats right?

  • @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 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 UA-cam and reddit are your best friends to learn anything

    • @ИванИваныч-н3у
      @ИванИваныч-н3у 2 роки тому +1

      Not worked on all versions of python, just new.

    • @ИванИваныч-н3у
      @ИванИваныч-н3у 2 роки тому

      What about dict update method?

  • @kleko
    @kleko 2 роки тому

    You should really defend why you mean one way is better than the other. You can't just say use enums instead of range(len()) without explaining the benefits. I really like list comprehension, but the way it was shown here makes it look like a one line mess creator.

  • @gomathikreddy350
    @gomathikreddy350 2 роки тому +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 роки тому +1

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

    • @gomathikreddy350
      @gomathikreddy350 2 роки тому

      Thank you. 😊🙏

  • @ChosenFate_
    @ChosenFate_ 2 роки тому +1

    You can also just do list.sort()

  • @ssshukla26
    @ssshukla26 2 роки тому

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

  • @axelmuller4341
    @axelmuller4341 2 роки тому

    After the first 3 "Tips" i quitted watching.. Everybody who writes Python Code for two months or longer does know all of these already.. completely useless

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

  • @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 2 роки тому +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 2 роки тому +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 2 роки тому +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.

  • @qinlingzhou8815
    @qinlingzhou8815 Місяць тому +1

    CNN is a septic tank. :)

  • @RicardoAmaralAndrade
    @RicardoAmaralAndrade 2 роки тому +2

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

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

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

  • @mattneed111
    @mattneed111 2 роки тому

    slow down, explain a little slower, your typing 1million mph and giving people who are learning 60 seconds to understand something thats not exactly basic.

  • @marazDNG
    @marazDNG 2 роки тому

    Point 7 is actually interesting. Point 5, 6, 8 are worth metioning but most of the other half are like python beginner level..

  • @ThiagoVieira
    @ThiagoVieira 2 роки тому

    I know us (the audience) we are able to pause the video to better analyse and understand what you just explained but some parts of your video passes so so fast that I had difficult to pause my tv right on the moment, like after you ran the program and the result was displayed on screen on the 10th tip, you left maybe less than half a second.
    It is just a smal tip for your next videos.

  • @tigranpapyan2348
    @tigranpapyan2348 7 місяців тому

    Actually, regarding the generator part, though it saves a lot of memory, it's way slower compared to lists

  • @lakshmanans-zb5sg
    @lakshmanans-zb5sg 3 місяці тому

    combine one and two : print ([0 if value

  • @deborshikashyap6745
    @deborshikashyap6745 2 роки тому

    How to create something like this I want user to write a variable = string..if they don't continue typing after putting an equal sign they'll get an error message

  • @sc0urge561
    @sc0urge561 2 роки тому +1

    One question though, are generators also faster than lists?

    • @patloeber
      @patloeber  2 роки тому +1

      no, the important point is that it requires less memory

  • @Lelouch_VI_Brittania
    @Lelouch_VI_Brittania Місяць тому

    Guys is there any pdf or full fledged youtube course where I can find more of this.

  • @bobbilderson8556
    @bobbilderson8556 Рік тому

    I think a lot of times I'd like my code to crash if I'm looking for an item that doesn't exist. .get() is situational and should not be recommended by default imo.

  • @paulosergioschlogl9550
    @paulosergioschlogl9550 5 місяців тому

    The {**d1, **d2} can be used with collections defaultdicts?

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

  • @abc_cba
    @abc_cba 3 роки тому +1

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

  • @VK_2002
    @VK_2002 2 роки тому

    Hi,
    Content is good and also demonstration would have been a bit slow I felt. Hope it will be rectified next time.

  • @bashvim
    @bashvim Рік тому

    What keyboard shortcut are you using run the python file in the Output tab below?

  • @Chuen666
    @Chuen666 8 місяців тому

    4:30
    print(sum(range(10000)))
    this one's bytes is only 28

  • @plumberski8854
    @plumberski8854 2 місяці тому

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

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

  • @athrvchaulkar
    @athrvchaulkar 2 роки тому +1

    Wah ♥️

  • @MegaArti2000
    @MegaArti2000 2 роки тому +1

    About the last tip: you should probably use SET instead of LIST if there were too many elements.
    Performance issues...

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

  • @mrsingh5351
    @mrsingh5351 2 роки тому +1

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

  • @eranzaksh
    @eranzaksh Рік тому

    Thank you! Isn't enumerate slower then range(len())?

  • @marcelomelo6349
    @marcelomelo6349 8 місяців тому

    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 8 місяців тому

      What do you think? Do you have more?

  • @AjSmit1
    @AjSmit1 2 роки тому

    wait... is that.. Diner Bros music in the background?

  • @_kopiter_
    @_kopiter_ 2 роки тому

    tutorial for complete beginners, python 101

  • @yasink18
    @yasink18 9 місяців тому

    Nothing new you have mentioned.. I am following the same thing

  • @chakkarapaniv
    @chakkarapaniv 4 роки тому +1

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

  • @Manker00
    @Manker00 Рік тому

    I don't quite understand why f strings are so praised. I would argue that the second print statement is both easier to read and write.
    print(f"Hello {name}")
    print("Hello", name)

    • @0LoneTech
      @0LoneTech Рік тому

      This is true for the specific case where you want to print the default formatting of every field with the same separator. Even then the actual output format is more evident in the f-string. f-strings make string formatting (as in str.format) more convenient, by accessing your local scope and evaluating expressions. It is possible to capture print output using an io.StringIO. Also, print can produce partial output if one of its arguments fails to convert.

  • @sturm1379
    @sturm1379 3 роки тому

    Great video.
    But the way this guy talks makes me nervous

  • @luckyboy-ih5hd
    @luckyboy-ih5hd 2 роки тому +1

    very helpful

  • @anuragmishra6475
    @anuragmishra6475 2 роки тому

    Brother I have one doubt??
    my_gen=(i for i in range(100000)) is a generator (undoubtedly), but isn't it a tuple also? I am confused, please explain.

    • @JeffGe05
      @JeffGe05 2 роки тому +1

      There are no tuple comprehensions. You have to explicitly call tuple() method on a generator expression to create a tuple.

  • @zacky7862
    @zacky7862 3 роки тому

    Could you please tell how to safely count or check the if the generators items are empty?

  • @gudguy1a
    @gudguy1a 10 місяців тому

    Still very relevant content, thanks for having this.

  • @davidvanleeuwen3274
    @davidvanleeuwen3274 2 роки тому +1

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

  • @chuzhong1214
    @chuzhong1214 2 роки тому

    Is the enumerate function really that much better? Having trouble finding convincing arguments other than “it’s more pythonic”. Performance also seems to be better using range/len … presumably because you don’t have to generate a whole list of indices first but rather just fetch the size of the array itself.

    • @0LoneTech
      @0LoneTech Рік тому

      enumerate creates (and usually unpacks) a tuple for each item, so it is quite plausible to have it operate slightly slower than a range iterator. range hasn't built the full list since Python 2 (back then the current range was known as xrange). You can also enumerate any iterable, not just sequences of known length. Mostly the difference does come down to clarity, and that's a pretty compelling argument IMHO. How long would it take you to recognize zip(itertools.count(), iterable) as the same function?

  • @munivoltarc
    @munivoltarc Рік тому

    Your explanation is very fast, slow down

  • @nul1
    @nul1 2 роки тому

    So, I was a smart python3 beginner then! 😎

  • @HKHforpeace
    @HKHforpeace 4 роки тому +3

    Really admire your work! Nice work mate

  • @faizalimuhammadzoda4731
    @faizalimuhammadzoda4731 3 роки тому +2

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

  • @onurkoc6869
    @onurkoc6869 2 роки тому

    You are Superman:) Thanks for all of sharing.

  • @ai.simplified..
    @ai.simplified.. 3 роки тому

    Delete the background music.

  • @TejasBangera
    @TejasBangera 4 роки тому +1

    Thank you, Subscribed to the channel

  • @matzeherd1343
    @matzeherd1343 2 роки тому

    Wenn deutsche versuchen, wie Amerikaner zu klingen 😅🤪

  • @alankritverma1839
    @alankritverma1839 7 місяців тому

    one of the best python videos.
    Really useful

  • @BPOCODER
    @BPOCODER 2 роки тому

    Please do type here for me it will be a great help if you do .

  • @bmansan
    @bmansan Рік тому

    Instead of enumeratet in first case just "for i in data: "

  • @shababe2243
    @shababe2243 2 роки тому

    Excellent information,Thanks

  • @alanwest546
    @alanwest546 2 роки тому

    I like to write code that is difficult to understand

  • @fahnub
    @fahnub 2 роки тому

    bro this was super helpful. thanks for this.

  • @Arson_Oakwood
    @Arson_Oakwood 6 місяців тому

    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.

  • @katateo328
    @katateo328 2 роки тому

    hahah, lam nong co can biet python hong ta :D

  • @sivaGpranesh
    @sivaGpranesh 3 роки тому

    Thanks for sharing the effective ways!
    Which is more effective?
    os.system() or subprocess.call/popen()
    Please let know.

  • @ichbrauchmehrkaffee5785
    @ichbrauchmehrkaffee5785 2 роки тому

    list comprehension is a nice thing,
    until you start to make gigantic list comprehensions, resulting in a line with more than 100 characters.
    Bin there, done that, now I'm reverting back to for-loops where necessary

  • @abdulqadar9580
    @abdulqadar9580 2 роки тому

    Please make complete playlist like these tips of python

  • @JL-pc2eh
    @JL-pc2eh 2 роки тому

    I am not on a level to understand everything yet :/
    I don't even optimize much of my exercice code, I'm glad if it workes xD

  • @saitejam3769
    @saitejam3769 2 роки тому

    Sir please post videos on nested loops and tips in nested loops

  • @mmxo2631
    @mmxo2631 2 роки тому

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

  • @akira_asahi
    @akira_asahi 2 роки тому

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

  • @werdergewinnt
    @werdergewinnt 2 роки тому

    Great tips but I'd like to have the video a bit slower so that you can think a second about what you just learned. It was a bit too fast

    • @patloeber
      @patloeber  2 роки тому

      thanks for the feedback!

  • @shashwatmangulkar1107
    @shashwatmangulkar1107 2 роки тому

    i also know a function which is the 'isinstance( obj , datatype)' in this function u can check if the obj given here is of the same datatype mentioned , this function returns bool = (True or False)

  • @tigrayrimey6418
    @tigrayrimey6418 3 роки тому +1

    Great point Sir! Do you have any python implementation code for the passive-aggressive algorithm from scratch for Multiclass classification?