DEV Community

Cover image for 10+1 Useful Python Code Snippets for Everyday Problems
Charalambos Ioannou
Charalambos Ioannou

Posted on • Updated on

10+1 Useful Python Code Snippets for Everyday Problems

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:

  1. Variable Swapping
  2. Select a Random Element
  3. Remove Duplicates in a List
  4. Find All Indices of an Element in a List
  5. Display the Current Date and Time in String Format
  6. Filter a List
  7. One Line Dictionary from List
  8. String to Integer
  9. Flatten a list
  10. Load file in a list
  11. 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
Enter fullscreen mode Exit fullscreen mode

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'])
Enter fullscreen mode Exit fullscreen mode

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]))
Enter fullscreen mode Exit fullscreen mode

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']
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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')]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)