15 Useful Snippets for your Daily life Python Problems
Digitizing, Generic Swapping, Hex_To_RGB, Print Same line Sort Dictionary, and many more useful snippets

Python is my most Favorite language and finds snippets for daily life Python problem is my hobby. I will brief 15 Useful Snippets for your Daily Life Python Problems. These snippets will help you in the daily Programming Problems that you face and write long code for them.
You will be familiar with most of the snippets but many of them will be new for you. These snippets are easy to learn and you freely use them in your code. Make a bookmark to this article for future use and let get started without wasting any further time.
1. Generic Swapping
I can bet you used a temp variable for swapping in many programming languages. But Python allows you to swap two values without any temp variable. Check the below code for example.
# generic swappingx = 10
y = 12x , y = y , x
print(x, y) # 12 102. Digitize into List
Digitizing means converting a number into an array or list. This comes in handy when you need to convert a large number into a list form.
Below code example use map() built-in method taking two arguments. In last we had converted the output result from the map method into the list.
# Digitizedef Digitizing(num):
return list(map(int, str(num)))num1 = 4858
num2 = 7804
print(Digitizing(num1)) # [4, 8, 5, 8]
print(Digitizing(num2)) # [7, 8, 0, 4]3. Easy Sorting
Sorting is a Part of everyday problems. We had to sort a list of numbers, names, and massive amounts of data and etc. Python had some good sorting methods that will save your time for writing manually a sorting function.
Below is the sorting example code in which I sort the list with two different sorting functions.
# Sorting with Built-in# method 1
List = [500, 300, 200, 100]print(sorted(List)) # [100, 200, 300, 500]#method 2List = [100, 500, 300, 400]List.sort()
print(List) # [100, 300, 400, 500]4. Way to Print on the Same Line
Another Solution for your everyday problem is Printing/Output data on the same line. We all Know that the Print() statement outputs the data on console line by line. What about if we are required to output on the same line?
Let suppose you making a console game in Python and you want to output a Print statement on the same line. Check out the below code example to get a solution for this.
# Good way to write on same lineimport syssys.stdout.write("Hello world ")
sys.stdout.write("Python is a Programming ")
sys.stdout.write("Langauge ")# Output
# Hello world Python is a Programming Langauge5. Printing String N Times
This snippet will save you from loops for printing string “N” times. In Python, you can multiple a string with an integer number and generate a sequence of it.
# Print N TIMES String# old method
for x in range(5):
print("👋")#👋👋👋👋👋# good method
print("👋" * 5) # 👋👋👋👋👋6. Find Anagrams
Anagrams are the word or phrase which are made by arranging them. Let say you are doing a text analysis in Python. You will need an Anagrams checking function. So why wasting time writing them. Just check out the following code example and use it for your daily anagram problem.
# Anagram checking
from collections import Counterdef isAnagrams(string1, string2):
return Counter(string1) == Counter(string2)print(isAnagrams("bc123", "445bc")) # False
print(isAnagrams("123abc","abc123")) # True7. Time of Execution
Every Programmer wants its Python program should be generic and had well execution performance. Below snippets will help you know the Time of Execution your program takes. We will use Time built-in Library in Python, Check out the example code below.
# Execuetion Time Calculating
import timest = time.time()def fun():
for x in range(100000):
print(x)fun()et = time.time()print("Execution take: ", et-st) # 7.870 sec8. Filter Unique Values
Let Suppose You had junk data and you need to find unique values or remove the duplicates. The first approach you will use is iterating each element and store them in the list and check that list with every element is it appear or not and etc. But these snippets will solve your problem in a second.
# Filtering Uniquedata= "111122233334444"
ndata = set(data)
filtered = "".join(ndata)print(filtered) # 34219. Make First Letter Capital
This is another daily problem-solving snippet you can make your String every word first Letter Capital. You had just used the title() method with your target string.
# Capital the First letterstring = "hy, i'm a codder"
print(string.title()) # Hy, I'M A Codder.string2 = "learn programming language"
print(string2.title()) # Learn Programming Language10. Hex to RGB
These are the most useful snippets for every Front end developer or designer. You can convert Hexadecimal Color Codes to RGB Code which is a format like that (Red, Green, Blue ). Check out the below code example to know how to do that.
#Hex to RGBdef Hex_To_Rgb(hex):
rgb = tuple(int(hex[x: x+2], 16) for x in (0, 2, 4))
return rgbprint(Hex_To_Rgb('FF5733')) # (255, 87, 51)
print(Hex_To_Rgb('33D8FF')) # (51, 216, 255)11. Sort Dictionary
We had seen snippets to sort a list Okay Cool. What about sorting Dictionaries ?. Dictionary is sort by either Key or value. We will see diction sort example code by using the same built-in sorting method with little modification.
# Sorting Dictionary#method 1
mydict = {3:"c", 2:"b", 1:"a"}
print(dict(sorted(mydict.items(), key=lambda x: x[1]))) # {1: 'a', 2: 'b', 3: 'c'}#method 2
mydict2 = [
{
"Name": "Haider",
"Age": 22,
"CGPA": 3.45
},{
"Name": "Charles",
"Age": 30,
"CGPA": 3.22
},{
"Name": "Isabella",
"Age": 21,
"CGPA": 3.12
}
]print(sorted(mydict2, key=lambda item: item.get("Name")))#Output
# [{'Name': 'Charles', 'Age': 30, 'CGPA': 3.22}, {'Name': 'Haider', 'Age': 22, 'CGPA': 3.45}, {'Name': 'Isabella', 'Age': 21, 'CGPA': 3.12}]12. Lower Case String
This snippet will show you how to make the lower case your string in a second using Python built-in method.
#Lower Case StringStr1 = "Python is a Programming Language"
Str2 = "PYTHON SNIPPETS FOR DAILY LIFE PROBLEM"#converting to lower case
print(Str1.lower()) # python is a programming language
print(Str2.lower()) # python snippets for daily life problem13. Check List is Empty or Not
This is another Problem we had a face when we receive data in the list from a function or HTTP server or anywhere and want to check whether or list is empty or not. The Below code example will show you the two ways to check the list is empty or not.
#checking list is empty or notmylst = list() # empty list
#method 1
if len(mylst) == 0:
pass#method 2
if not mylst:
pass14. Cloning a List
This snippet will show how to copy a list to another list using the simple copy method and deep copy method. Now you no longer need to used Loops for copying a list check out the below example code.
# List Cloning
import copymylist = [5, 4, 2, 99, 100, 123, 434, 566]#method 1clone_list1 = copy.copy(mylist)clone_list2 = copy.deepcopy(mylist)print(clone_list1) # [5, 4, 2, 99, 100, 123, 434, 566]
print(clone_list2) # [5, 4, 2, 99, 100, 123, 434, 566]#method 2clone_list3 = [x for x in mylist]
print(clone_list3) # [5, 4, 2, 99, 100, 123, 434, 566]15. Two List To Dictionary
This snippet code you understand by its name we will convert the two list into a dictionary using the zip() method. Zip method first argument will be a key and the second will be valued.
# Two List to Dictionary
keys = [1, 2, 3]
values = ["Python", "JavaScript", "Dart"]dicti = dict(zip(keys,values))print(dicti) # {1: 'Python', 2: 'JavaScript', 3: 'Dart'}Final Thoughts
I hope you had enjoyed these snippet codes and use them in your project. Make a bookmark for this article for future use. These are common snippets that we need for daily life Python Problems. Feel Free to share your response and snippets with the community. Happy Python Coding!
What Next?
Never stop learning, check out my other Programming related articles, I hope you will enjoy them also.
More content at plainenglish.io
