Python: Tips and Tricks

Tram Ho

In this article, I will introduce everyone to some tips & tricks in Python. Hope to help everyone when working with Python

  1. Split the elements list, dict, set into separate lines
  • To easily figure out the usage and benefits of this tip, I have the following code:

  • Whenever you change these list names , it will be difficult to see what you changed using git diff. This is because most Version Control Systems detect change history based on line of code. To overcome this weakness, instead of writing on one line, divide it into many lines, as follows:

  • When writing like this, using git diff you can easily spot which elements in the list names have been added, removed, or modified. This is a small change but has many benefits, making it easier for everyone on the team to review your code.
  1. Use a comma after the last element
  • This is a useful tip for adding, editing, or deleting an element in a list, dict, or set. Specifically as follows, I have the code:

  • If you add another element, ‘Dung’ , to the list names , you will have to edit two lines of code:

  • This makes it difficult to use git diff to detect code changes, whether someone has added an element, or has edited an element in the list. To fix this, add a comma after the last element in the list, dict or set:

  1. Comprehensions tricks
  • Use with list:

  • Use with set:

  • Use with dict:

  1. Use UUID library
  • If you need to generate uuid, can use uuid library, this library will generate 1 128bit random string and is unique. In fact, there will be about 2¹²² of uuid string generated from this library, usage is as follows:

Share the news now

Source : Viblo