21 MORE nooby Python habits
Key Takeaways
The video discusses 21 nooby Python habits to avoid, covering topics such as code optimization, data analysis, file manipulation, input/output operations, Python best practices, and code readability, using tools like PyCharm, NumPy, Pandas, Pathlib, and JSON.
Full Transcript
welcome to my list of 21 more newbie python habits I'm also giving away pycharm licenses so get your hashtag pycharm down in the comments to enter newbie habits are things that noobs do that doesn't mean they're wrong or bad or that you can't or shouldn't use them but nonetheless they tip off other developers to your inexperience and avoiding them tends to improve your code so whether you're brand spanking new to python or just trying to keep that awesome Tech job you somehow got let's Dive In newbie thing number one manually rounding inside a print statement you computed some value and it's time to print it out but it's a floating point value if you just print it out as is it's too many digits too much clutter so you just round it right instead just use a format specifier number two repeatedly converting to and from numpy arrays often accidentally in most data analysis situations the best thing is usually to just immediately convert your data into numpy arrays or pandas data frames then just make sure you stick to all numpy or pandas functions it's a pretty common mistake to actually use a non-numpy function like the built-in Max which results in even worse performance than using Macs on a list number three manipulating paths as strings for obvious reasons it's very common to represent a path as a string so there's the obvious temptation to do string operations to manipulate the paths but this approach is highly error prone instead consider using the built-in pathlib pathlib already has built-in most of the common file and directory manipulations that you would want to do number four writing i o functions that take the path instead of an i o object there's nothing really wrong with having a convenience function that does this but what you should really do is have a separate function that does all of the writing operations so this function does all of the logic of writing to the file and this function is just a convenient wrapper around it the reason for doing this especially if you're writing a library is that people might not want to open a file or they might want to be writing to a different kind of i o object like to a zip file to a network connection or to a string by providing this version of the function you allow people to write to whatever they want to instead of just to a file and speaking of writing to a string that brings us to our next newbie habit concatenating strings with plus the plus operation on a string copies the string so in this for loop I end up making 100 copies of a larger and larger string instead use a string i o object this uses a growing in-memory buffer to minimize the number of copies of the string data and it has an interface just like a file object that you'd get from open and once you're ready to convert the buffer back into an actual string object call get value number six put a finger down if you've never done this one using eval as a parser through dubious means you've got a string with a data structure in it just pass it to eval what could possibly go wrong well of course the answer is eval is bad and you should feel bad for trying okay okay eval does have some legitimate uses but parsing data from a string isn't one I would probably use in production instead consider using an actual parsing Library like the built-in Json number seven and this one really pains me to see storing your function inputs and or outputs AS Global variables if you're reading from a global and using it to change something about how your function works then consider it might be better if it's just an input parameter and if you're writing to a global variable it should probably be somewhere in your return value hey while you're here did you know that I'm available for Consulting that's right self promo my team does python Consulting Contracting training and interview prep if you're interested visit mcoding.io number eight thinking and an or return bools you may not have ever printed out the results of an and or an or because you typically just use them in if statements but if you did you might have been surprised at the results you don't get a true or false in general ore Returns the first truthy thing or the last falsy thing and and Returns the first falsy thing or the last truthy thing number nine single letter variables there are of course cases where single letter variables are fine a single underscore to denote something calling a loop variable I common conventions like X Y and Z coordinates or even well-known math formulas no what I'm talking about is a whole function where everything is just a single letter or maybe two with just a few carefully thought out variable names it would be so much easier to understand number 10 using both div and mod instead of divmod if you're doing like math I guess there's a decent chance that you'll want to divide by a number and know both the quotient and remainder and that's what div mod does it gives you both a quotient and the remainder without repeating the calculation number 11 not knowing about properties a lot of noobs especially people coming from java are in the habit of writing Getters and Setters for every variable the more pythonic thing is to just leave the variable as part of the public interface but sometimes we use Getters and Setters because we want to actually do something in them in that case having a separate get and set function does make sense but doing that means that in order to access the value I'm now calling functions set X and get X instead of the more intuitive.notation well that's exactly what a property lets us do now because of descriptor magic we can just say object.x equals 42 and that will actually call the setter with the value being 42 and On a related note number 12 having expensive properties cool cool you learned what a property is and now it's time to save two characters on every function call by converting them into properties slow down there it's not about saving characters anything that takes much longer than just a normal attribute access shouldn't be turned into a property if you have a function that might be very expensive offensive make it look expensive number 13 inserting or deleting while iterating here We're looping over the dictionary and while that iteration is in progress we try to delete a key for a dictionary doing this is going to raise a runtime error but for other data types especially see extension types this might just do something very weird and not throw any error replacing or modifying a value on the other hand is typically fine another approach is to keep a set of keys that you're going to delete Loop over the dictionary and add anything that you want to delete into the to delete set then once you're done delete all of the keys afterwards number 14 and I know this will be controversial any use of filter or map the reason is that they encourage you to write code that looks like this in general you can replace any filter like this and you can replace any map like this these generator comprehensions are lazy just like filter and map and they produce the same elements and bonus points if you were just immediately going to convert that to a list instead you could use a list comprehension which is even more readable and it's tomorrow who could have guessed that yelling python into a microphone for two hours was bad for your voice but you're worth it 14 down let's keep going number 15 defining too many or inappropriate Dunder methods some of them like in a knit or a hash make perfect sense to Define for most classes but the person class does not represent any kind of number or thing that naturally has a plus operation associated with it but this code goes ahead and defines IAD to make plus equals mean make these two people friends don't use a Dunder method to accomplish this task just use a normal function with a good name number 16 trying to parse HTML or XML using regular Expressions it's not that you made a mistake that your regular expression is bad or that you're not smart enough to come up with the complete one that handles all the edge cases it's literally impossible to create a regular expression that can parse HTML because HTML is not a regular language instead you're going to need an actual parser you could use something like Python's built-in HTML parser or you could reach for more full featured third-party Library like beautiful soup which of course has a parser inside of it 17. not knowing about raw string literals in most rings it doesn't matter but specifically for Windows paths and in regular expressions using literal backlashes is very common plop down an r in front of your string to make it a raw string literal raw strings ignore Escape sequences making regular Expressions much easier to read 18. thinking that super means parent you might think that the supercall is going to call the roots version of F and in most cases you'd be right but not in all cases and the reason is that someone could inherit from your class this instance of C is also an instance of a but when we call F we see that the chain of super calls goes from C to A to B to root in particular this super column side of a right after printing a dot f sent us to The Sibling class b not to A's parent root I've got a whole video on super if you'd like to hear more 19. passing structured data around as a raw dictionary or Tuple you do some calculation take a measurement or summarize some data if these values are meaningful and always need to stick together then most likely this should be a class and you should give it a name if you were returning a dictionary before a data class is probably what you want and if you're returning a tuple then a named Tuple is probably what you want number 20 using collections named Tuple instead of typing named Tuple back in the day this was a best practice because it allowed you to give Tuple elements good names but nowadays the typing named Tuple is a much more readable way to do the same thing it actually looks like a class definition it's easy to read and doesn't rely on strings and as always saving the best for last number 21 import time side effects please please please don't print something when I import your module even if your library can also be used as a script and that's the behavior that you want when you run the script use the deaf main if name main idiom to hide it behind a main function that's another one where I've got a whole video explaining the benefits of doing this and that's 21. you must really love the sound of my voice or maybe you just like my content in which case don't forget to subscribe and become one of my patrons on patreon pitching for more newbie habits check out my first newbie Habits video as always thank you to my patrons and donors for their support slap that like button an odd number of times and I'll see you next time
Original Description
Get better at Python by ditching these habits.
Embrace the Zen of Python and leave your nooby habits behind! Improve your code and your prestige and learn how to master Python.
CONTEST CURRENTLY CLOSED!
OFFICIAL CONTEST RULES:
1. All entries must comply with the YouTube community guidelines ( http://www.youtube.com/t/community_guidelines) and YouTube Terms of Service (http://www.youtube.com/static?gl=US&template=terms). Entries that violate YouTube guidelines are automatically disqualified.
2. YouTube is not a sponsor of the contest and viewers are required to release YouTube from any liability related to the contest.
3. Privacy notice: no personal data will be collected for this contest.
4. In order to enter, you must (a) be one of my subscribers, AND (b) make a top-level comment to the video including #pycharm somewhere in the comment.
5. The contest is free, there is no fee required to enter.
6. Winners will be chosen randomly 1 week after the date the video went live from all users who have entered and not been disqualified.
7. Each winner will be notified via a comment reply from me that details what prize was won (e.g. "Congratulations! You have won XYZ. Please email me."). I will ask the winner to contact me by email, and I will reply through email with a random token which must be posted as another reply to the winning comment from the winning account in order to verify account ownership and prevent fraud.
8. Each winner will have 72 hours to respond AND prove account ownership or their prize is automatically forfeited and another winner will be chosen.
9. A winner can only win 1 prize per contest.
10. The prize pool for this contest is: 2 licenses ("Free 1-Year Personal Subscription") to any of these JetBrains IDEs: AppCode, CLion, DataGrip, DataSpell, GoLand, IntelliJ IDEA Ultimate, PhpStorm, PyCharm, ReSharper, ReSharper C++, Rider, RubyMine, WebStorm, or dotUltimate. A prize consists of 1 license, which will be delivered in the form of a redeemable co
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from mCoding · mCoding · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Goodbye, List! Type hinting standard collections - New in Python 3.9
mCoding
Python's comma equals ,= operator?
mCoding
Finding Primes in Python with the Sieve of Eratosthenes
mCoding
Find the First Missing Positive Int | Hard Interview Question on LeetCode
mCoding
JSON Tutorial Python | Basic Python Recipes
mCoding
Simulating Brownian Motion in Python
mCoding
The Single Most Useful Decorator in Python
mCoding
The Fastest Way to Loop in Python - An Unfortunate Truth
mCoding
Numpy Array Broadcasting In Python Explained
mCoding
Brownian Motion Single Path Zoom
mCoding
Brownian Motion Fractal Zoom
mCoding
Magic Methods - Making Python builtins work with your classes
mCoding
50 Million Primes In 5 Seconds - Segmented Sieve of Eratosthenes
mCoding
The Hottest New Feature Coming In Python 3.10 - Structural Pattern Matching / Match Statement
mCoding
How Fast is Python's Sort? Performance Testing
mCoding
C++ First Missing Int, faster than 100%!
mCoding
[April Fools 2021] Python 4.0! New old print, mandatory static typing, StackOverflow integration
mCoding
Python dataclasses will save you HOURS, also featuring attrs
mCoding
C++ Sudoku Solver in 7 minutes using Recursive Backtracking
mCoding
Every PROOF you've seen that .999... = 1 is WRONG
mCoding
Python's sharpest corner is ... plus equals? (+=)
mCoding
Binary Search - A Different Perspective | Python Algorithms
mCoding
The Best Way to Check for Optional Arguments in Python
mCoding
Local and Global Variable Lookup Weirdness in Python
mCoding
Efficient Exponentiation
mCoding
How To Install Python for Data Science
mCoding
0.1 + 0.2 is NOT 0.3 in Most Programming Languages
mCoding
Python 3.10's new type hinting features
mCoding
Python 3.10's Quality of Life improvements
mCoding
Introducing mZips! Python Zip and Zip Longest
mCoding
Match statement tips
mCoding
Using except: is a HUGE mistake
mCoding
Python + YouTube API | Automating descriptions
mCoding
Anaphones, phonetic anagrams
mCoding
Cracking passwords using ONLY response times | Secure Python
mCoding
Python f-strings can do more than you thought. f'{val=}', f'{val!r}', f'{dt:%Y-%m-%d}'
mCoding
Diagnose slow Python code. (Feat. async/await)
mCoding
Python MD5 implementation
mCoding
Salting, peppering, and hashing passwords
mCoding
x to bool conversion in Python, C++, and C
mCoding
You should put this in all your Python scripts | if __name__ == '__main__': ...
mCoding
Find the Skyline Problem with C++ Solution Explained
mCoding
The ONLY C keyword with no C++ equivalent
mCoding
Should you use "not not x" instead of "bool(x)" in Python? (NO!)
mCoding
Multiple Assignments in Python
mCoding
Why I don't like Python's chained comparisons
mCoding
Automated Testing in Python with pytest, tox, and GitHub Actions
mCoding
You can pip install directly from GitHub
mCoding
__new__ vs __init__ in Python
mCoding
Metaclasses in Python
mCoding
The easy way to keep your repos tidy.
mCoding
Which Python @dataclass is best? Feat. Pydantic, NamedTuple, attrs...
mCoding
Python __slots__ and object layout explained
mCoding
C++ cache locality and branch predictability
mCoding
Avoiding import loops in Python
mCoding
25 nooby Python habits you need to ditch
mCoding
Python staticmethod and classmethod
mCoding
Building a Python app with Anvil to email me if my website goes down (includes paid features)
mCoding
31 nooby C++ habits you need to ditch
mCoding
Interviewing the creator of C++, Bjarne Stroustrup
mCoding
More on: LLM Foundations
View skill →Related AI Lessons
⚡
⚡
⚡
⚡
Spring AI Tutorial — Your First REST Endpoint with OpenAI (2026)
Dev.to AI
10 ChatGPT Prompts for Job Seekers: Resumes, Interviews & Career Growth
Medium · ChatGPT
Lost in Transcription: The Week the Machine Started Lying
Medium · AI
From Sci-Fi to Source Code: Why the Future of LLMs Looks Like Pure Number Theory
Medium · LLM
🎓
Tutor Explanation
DeepCamp AI