r/pythontips • • Mar 12 '23

Long_video 25 Tips/Tricks to Write Better Python Code!

I created a long video on youtube pertaining to 25 tips to help you write better code in Python, this can help you in a professional setting, or in coding interviews. These tips include ways to improve the readability/maintainability of your code, improve efficiency, and learn aspects of the Python language you may have never heard of!

There are many tips which I summarize here:

  • Organize Imports Properly

  • Learn to Use PDB

  • Use the new Match/Case Statements

  • Learn about the Bisect Library

  • Learn about the Walrus Operator

  • Know when to use Enumerate over Range

  • Utilize Numpy for Efficiency

  • cProfile for finding Bottlenecks

  • Catch-all Unpacking to improve readability

  • Prefer f-strings over other string formatting methods

  • Naming Variables properly

  • Know when to use Generators over Lists

  • .get() Method to help with dictionaries

  • Specific Exceptions as opposed to broad exceptions

  • .zip() Method when iterating over multiple lists can help

  • Loops with Else Statements, not a very well-known feature in Python

  • Write Docstrings for complicated functions in practice

  • Be cautious with Python Dict Order

  • List Comprehension better practice

  • Use Dictionary Comprehension, a lot of people do not do this for some reason

  • Avoid one-line if/loops (seen a lot in hackerrank and leetcode)

  • Don’t check for empty containers/sequences, use "if not" instead

  • Split Long Lines of more than 79 chars

  • Add new line to the end of a file always in accordance with pep8

  • … Practice these points in your projects and share with teammates in code reviews :)

Would really appreciate anyone watching the video. I definitely think it can help new beginners. If you like such content please subscribe to the channel it would mean a lot!

Here is the video on youtube: https://www.youtube.com/watch?v=2U98PgL-kuI

Channel is here: https://www.youtube.com/@mmshilleh

Of course, comments are always appreciated, thanks Reddit!

65 Upvotes

Duplicates