This is a short list of less known tricks that I use in Python

Delete repeated elements of a list

An easy way to delete repeated elements from a list is to convert it to a set and then convert to a list. This works because a set can’t have repeated elements.

a = [1,1,2,3]
print(list(set(a)))
[1, 2, 3]

Serve static files with HTTP

The python interpreter has the SimpleHttp module which is very useful. If you run this command on a directory you will be able to access to the files thought http.

python3 -m http.server 8080

Join a list of strings with a string separator

A useful not so known str function it’s the join method. You can use this to join a list with a string

",".join(["1","2","3"])
'1,2,3'

With this you don’t have to control if it’s the last element of the list to add the separator

Use a dictionary to pass parameters to a function

Sometimes you need to send data to functions and you need to adapt the same data to the function parameters, you can do this with the operator ** . This operator passes the values of the dictionary to a function using the key as a parameter name:

def function1(param1):
   print(f"function1:{param1}")

def function2(param2):
   print(f"function2:{param2}")

data ="hi"
data_function1 = {"param1": data}
data_function2 = {"param2": data}
function1(**data_function1)
function2(**data_function2)

Make ifs more readables

On of the zen of python is “Readability counts.” . This example shows a correct way to check None and False values on an if

# Wrong way
value = None
if value is None:
   print("No value")

# Wrong way
value = False
if value == False:
   print("Value False)

# Correct way
if not value:
   print("value false or None)