Hello Everyone,
Python is the most frequently used programming languages for Machine Learning, Data Science and Analytics and even Web Development.
This post lists 10 + 1 bonus Python code snippets which will assist with common and everyday problems. Also, these code snippets are only a single line!
Here are the sections for quick navigation:
- Variable Swapping
- Select a Random Element
- Remove Duplicates in a List
- Find All Indices of an Element in a List
- Display the Current Date and Time in String Format
- Filter a List
- One Line Dictionary from List
- String to Integer
- Flatten a list
- Load file in a list
- Bonus
1. Variable Swapping
One of the most common problems that we face each day is how to swap two variables. Algorithms and data structures have taught us that we need a third temporary variable in order to swap two variables. However this is not needed in Python:
# Instead of this:
tmp = var1
var1 = var2
var2 = tmp
# We can do this:
var1, var2 = var2, var1
2. Select a Random Element
The following code snippet yes depends on a library however it can provide cryptographically secure random choices and a usage for this is for generating a passphrase from a wordlist.
import secrets
res = secrets.choice(['cat', 'dog', 'horse', 'car'])
Note: secrets was added in Python 3.6. On older versions of Python you can use the random.SystemRandom
from the random library.
3. Remove Duplicates in a List
This one liner is used to remove duplicates in a list when the ordering of the elements is not important.
res = list(set([1,1,1,2,3,3,3]))
4. Find All Indices of an Element in a List
The following snippet uses list comprehension to return all the indices of the search element instead of just the first occurrence as done by .index()
.
lst = [1, 2, 3, 'Alice', 'Bob', 'Alice']
res = [i for i in range(len(lst)) if lst[i]=='Alice']
5. Display the Current Date and Time in String Format
This one liner imports the datetime
library, gets the current date and time and converts it into a string. This can be frequently used to integrate the date and time into various results shown to a user.
import datetime; res = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
6. Filter a List
List comprehension has become the Pythonic way of filtering a list. Here is the code snippet:
lst= [5,6,7,8,10,20,30]
res = [i for i in lst if i > 10]
7. One Line Dictionary from List
The following code snippet creates a dictionary with the list indices as key and their elements as values.
lst = ["a", "b", "c", "d"]
res = dict(enumerate(lst))
8. String to Integer
Using the map
method we can convert a string list containing numbers into integers. This can be useful when taking input from the user as a string and need to convert it into integer.
lst = ["5", "6", "7", "8", "9"]
res = list(map(int, lst))
9. Flatten a list
Machine Learning experts, and Data Scientists frequently deal with multi-dimensional lists and might need to convert these data into one-dimensional. The following one-liner does this without the use of any libraries like numpy
.
lst = [[1],[2],[3]]
res = [item for sublist in lst for item in sublist]
10. Load file in a list
The following one liner reads a txt file and adds each line as a new element in a list.
lst = [line.strip() for line in open('input_file.txt', 'r')]
Bonus
These libraries have saved me tons on time in my development process and can still be categorised as one-liners since just one command is needed for these to work.
Pipreqs
This library comes in handy when you need to generate a requirements file. It automatically generates the requirements.txt
file with all the import libraries and versions you are using in your current project only.
Here's how to generate your requirements.txt
file.
pip install pipreqs
pipreqs /path/to/project/location
Pyforest
With this library you are able to use all your favorite Python libraries without importing them before. It contains the most popular Python libraries such as pandas
, matplotlib
, seaborn
, numpy
and sklearn
. The best part of this package is that if you don't use a library, it won't be imported.
Here's how to use Pyforest in your own project
pip install --upgrade pyforest
python -m pyforest install_extensions
Then simply add import pyforest
in your project and you are good to go.
THATS ALL! I hope you enjoyed reading this article and found the content helpful 😃.
Top comments (0)