10+1 Useful Python Code Snippets for Everyday Problems
Tags: python, beginners, codenewbie, programming
Published: 2022-01-06 09:36:41


Hello Everyone,

Python is the most frequently used programming languages for Machine Learning, Data Science and Analytics and even Web Development. 
<!--This results in having various libraries that help coders develop applications faster but at the same cause too much dependency on a library. -->
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](#1-variable-swapping)
2. [Select a Random Element](#2-select-a-random-element)
3. [Remove Duplicates in a List](#3-remove-duplicates-in-a-list)
4. [Find All Indices of an Element in a List](#4-find-all-indices-of-an-element-in-a-list)
5. [Display the Current Date and Time in String Format](#5-display-the-current-date-and-time-in-string-format)
6. [Filter a List](#6-filter-a-list)
7. [One Line Dictionary from List](#7-one-line-dictionary-from-list)
8. [String to Integer](#8-string-to-integer)
9. [Flatten a list](#9-flatten-a-list)
10. [Load file in a list](#10-load-file-in-a-list) 
11. [Bonus](#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:

```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.

```python
import secrets
res = secrets.choice(['cat', 'dog', 'horse', 'car'])
```
<u> Note:</u> 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.

```python
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()`. 
```python
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.

```python
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:
```python
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.
```python
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.

```python
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`.

```python
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.

```python
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.
``` bash
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

``` bash
pip install --upgrade pyforest
python -m pyforest install_extensions
```
Then simply add `import pyforest` in your project and you are good to go.

<br/><br/>
THATS ALL! I hope you enjoyed reading this article and found the content helpful :smiley:.