12 Python Tips and Tricks For Writing Better Code | by Pavel Tech | Towards Data Science

F-Strings provide a concise and convenient way to embed Python expressions inside string literals for formatting.
First, let’s define two variables name and age that you want to include in our print statement.
name = "Pavel"age = 23
To not deal with string concatenation or using commas inside the print statement, you can use Python’s improved String formatting syntax “f-Strings” which has been released with Python 3.6.
Simply put a lowercase or uppercase letter “f” before the string with the variables or expressions inside the curly braces.
F-Strings are a great new way to format strings and are more readable, faster, concise, and less prone to error than other ways of formatting!
The Python help function is used to look up the documentation of modules, functions, classes, keywords etc.
Simply pass an object inside the help function to retrieve the documentation for that object:
The default sys module contains a function getsizeof that takes an object and returns its size in bytes. The object can be of any type.
Only the memory consumption directly attributed to the object is accounted for and not the memory consumption of objects it refers to.
Normally to check more than two conditions, you would have to use logical operators such as and/or
if a < b and b < c:
In Python, there is a better way to write this using Comparison operator Chaining.
The chaining of operators can be written as follows:
if a < b < c:
List comprehensions are another and often times more elegant way of making lists.
Rather than creating an empty list and adding each element to the end, you can simply define the list and its contents at the same time by following this format:
new_list = [expression for item in iterable (if conditional)]
In Python, it is possible to multiply not only numbers but strings too.
You can assign multiple values to multiple variables by separating variables and values with commas:
This also works when destructuring/unpacking sequences such as lists or tuples and is a more elegant way of assigning elements of a sequence to individual variables as there is no need to use a loop or separately index each element of the sequence.
In many other programming languages swapping the values of two or more variables could only be done by defining an additional temp (temporary) variable.
Say you want to swap x and y:
temp = xx = yy = temp
In Python, there is a simple one-line construct to swap variables, similar to the concept of assignments of values to multiple variables in one-line.
The following code does the same as above but without the use of any temporary variable:
Enum is a class in Python for creating enumerations, which are a set of symbolic names attached to unique, constant values.
In order to create an Enum, it is necessary to create a class which is the name of the Enum that you want.
All that is left to do is list the variables and set them equal to the values that you want:
To access the enum memberPaulas an example, you can just do Person.Paul which will return 0 .
In Python, the example above can be shortened by listing the variables beside each other and setting them equal to the range function:
Often when looping through a list you want to access not only the index with a position in the list but the actual element as well.
Let’s define a list of characters:
x = ['a', 'b', 'c']
Instead of looping through it the standard way, to access the element and index:
Enumerate is a built-in function of Python and allows us to loop over an iterable and have an automatic counter. It essentially pairs every element in our list with the corresponding index. Most of the newcomers and even some advanced programmers are unaware of it.
You can change the variables i and v to variable names that you might prefer. For example, for index, count in enumerate(x).
dir() is a powerful inbuilt function in Python3, which returns a list of the attributes and methods of any object i.e. functions, modules, strings, lists, dictionaries etc.
This can be very useful when having little to no information about the module and helps to learn new modules faster.
The dir() is often used for debugging purposes. The ability of dir() to list out all the attributes of the parameter passed, is really useful when handling a lot of classes and functions, separately.
Sometimes called the Splat or Scatter operator * works when the arguments in a list/tuple need to be unpacked for a function call requiring separate positional arguments.
For instance, the built-in range() function expects separate start and stop arguments. You can use the * operator to unpack the arguments out of a list or tuple when writing a function call:
Let’s define a simple list x = [1,2,3,4,5]
A common example of unpacking operator would be using print:
print(*x) // Result: 1 2 3 4 5
This simply prints out each element of the list beside each other separated by space as the unpack operator takes all the elements in the list and passes them as a parameter, so the translation of the code above would be print(1,2,3,4,5).
This Python trick is used quite often in functions, to ‘pack’ all the arguments that the method call receives into one single variable.
The function func above can take an unlimited amount of arguments (args[0] and args[1] would give you the first and second argument respectively).
In a similar way, dictionaries can deliver keyword arguments with the ** operator.
Let’s define a Python dictionary called person:
person = {"name": "Paul", "age": 23, "location": "London"}
You can use the ** operator to pass in a dictionary to a function.
The passed-in dictionary will decompose the keys as the function keyword arguments and then take the value as the actual value that’s passed for that argument.
Thank you for reading and I hope you found this article useful!
If there are tips you think I should have included or other suggestions then please do comment. 💬
Happy coding! 💻☕️