How-to articles, tricks, and solutions about PYTHON
How do I get the number of elements in a list (length of a list) in Python?
To get the number of elements in a list in Python, you can use the len() function.
Limiting floats to two decimal points
To limit a float to two decimal points, you can use the round() function.
How can I randomly select an item from a list?
You can use the random module's choice function to select a random element from a list.
How do I check if an object has an attribute?
You can use the hasattr function to check if an object has an attribute.
Calling a function of a module by using its name (a string)
To call a function from a module by using its name as a string, you can use the importlib module.
How to leave/exit/deactivate a Python virtualenv
To leave a Python virtual environment, you can use the deactivate command.
How to print without a newline or space
To print without a newline in Python, you can use the end argument for the print() function.
Class (static) variables and methods
In Python, class variables are variables that are shared by all instances of a class.
How do I lowercase a string in Python?
You can use the lower() method to lowercase a string in Python.
How do I get a substring of a string in Python?
To get a substring of a string in Python, you can use the string[start:end] notation.
How do I get the last element of a list?
To get the last element of a list, you can use negative indexing.
Check if a given key already exists in a dictionary
To check if a given key already exists in a dictionary, you can use the in keyword.
How can I remove a key from a Python dictionary?
You can use the del statement to remove a key-value pair from a dictionary in Python.
Renaming column names in Pandas
To rename the column names of a Pandas DataFrame, you can use the DataFrame.rename() method.
Find the current directory and file's directory
To find the current directory in Python, you can use the following code:
How can I access environment variables in Python?
You can use the os module in Python to access environment variables.