Python is the top programming language and extremely helpful in daily life problem-solving. In this article, I will brief you on 22 useful snippets to code like a pro in Python. This snippet will also help you with daily life programming problems.
Some of the snippets you might have come across before and some will be new and interesting for you. These snippets are easy to learn.
1. Get Vowels
This snippet will found vowels “a e i o u” in a string. This will come in handy when you are finding or detecting the vowels.
def get_vowels(String):
return [each for each in String if each in "aeiou"]
get_vowels("animal") # [a, i, a]
get_vowels("sky") # []
get_vowels("football") # [o, o, a]
2. Capitalizing First Letter
This snippet will be used for capitalizing every first letter of the character in the string. It can work on a string with one or more than one character. This will comes in handy in Text analysis r writing data to files or etc.
def capitalize(String):
return String.title()
capitalize("shop") # [Shop]
capitalize("python programming") # [Python Programming]
capitalize("how are you!") # [How Are You!]
3. Print String N Times
This snippet can print any string n times without using any python loops.
n=5
string="Hello World "
print(string * n) #Hello World Hello World Hello World Hello World Hello World
4. Merge two Dictionaries
This snippet will merge two dictionaries into one. Check the following code to know how this method works.
def merge(dic1,dic2):
dic3=dic1.copy()
dic3.update(dic2)
return dic3
dic1={1:"hello", 2:"world"}
dic2={3:"Python", 4:"Programming"}
merge(dic1,dic2) # {1: 'hello', 2: 'world', 3: 'Python', 4: 'Programming'}
5. Calculate execution Time
This snippet is useful for you when you want to know how much time your program or a function takes to complete its execution.
import time
start_time= time.time()
def fun():
a=2
b=3
c=a+b
end_time= time.time()
fun()
timetaken = end_time - start_time
print("Your program takes: ", timetaken) # 0.0345
6. Swap the values
This snippet is a quick way to swap two variables without using a third one.
a=3
b=4
a, b = b, a
print(a, b) # a= 4, b =3
7. Check duplicates
This method is the fastest way to check duplicates in the list.
def check_duplicate(lst):
return len(lst) != len(set(lst))
check_duplicate([1,2,3,4,5,4,6]) # True
check_duplicate([1,2,3]) # False
check_duplicate([1,2,3,4,9]) # False
8. Filtering False Values
This snippet is used to remove any falsy values in a list like false,0,None, “ ” . Check the below code to know how this method works.
def Filtering(lst):
return list(filter(None,lst))
lst=[None,1,3,0,"",5,7]
Filtering(lst) #[1, 3, 5, 7]
9. Byte Size
This snippet will return the length of the string in byte size. This will comes in handy when you want to know the size of any string variable.
def ByteSize(string):
return len(string.encode("utf8"))
ByteSize("Python") #6
ByteSize("Data") #4
10. Memory Usage
This snippet is used to get the memory used by any variable in python.
import sys
var1="Python"
var2=100
var3=True
print(sys.getsizeof(var1)) #55
print(sys.getsizeof(var2)) #28
print(sys.getsizeof(var3)) #28
11. Anagrams
This snippet is useful to check if the string is an anagram or not. An anagram is the words that will be the same if we rephrase them.
from collections import Counter
def anagrams(str1, str2):
return Counter(str1) == Counter(str2)
anagrams("abc1", "1bac") # True
12. Sorting List
This snippet will sort your list. Sorting is a common task that can be done with multiples lines of code with a loop but you can speed up your work by using a built-in sorting method Want to know How? check the below code.
my_list = ["leaf", "cherry", "fish"]
my_list1 = ["D","C","B","A"]
my_list2 = [1,2,3,4,5]
my_list.sort() # ['cherry', 'fish', 'leaf']
my_list1.sort() # ['A', 'B', 'C', 'D']
print(sorted(my_list2, reverse=True)) # [5, 4, 3, 2, 1]
13. Sorting Dictionary
This snippet will be used to sort the dictionary. check out the following code to know how it works.
orders = {
'pizza': 200,
'burger': 56,
'pepsi': 25,
'Coffee': 14
}
sorted_dic= sorted(orders.items(), key=lambda x: x[1])
print(sorted_dic) # [('Coffee', 14), ('pepsi', 25), ('burger', 56), ('pizza', 200)]
14. Retrieving the Last Element of the List
This snippet will show how to retrieve the last element of the list.
my_list = ["Python", "JavaScript", "C++", "Java", "C#", "Dart"]
#method 1
print(my_list[-1]) # Dart
#method 2
print(my_list.pop()) # Dart
15. Comma Separated to String
This snippet code will convert the comma-separated list into a single String. This comes in handy when you want to join the whole list with a string.
my_list1=["Python","JavaScript","C++"]
my_list2=["Java", "Flutter", "Swift"]
#example 1
"My favourite Programming Languages are" , ", ".join(my_list1)) # My favourite Programming Languages are Python, JavaScript, C++
print(", ".join(my_list2)) # Java, Flutter, Swift
16. Palindrome Checking
This snippet will show you how to check palindrome in python fast.
def palindrome(data):
return data == data[::-1]
palindrome("level") #True
palindrome("madaa") #False
17. Shuffle a list
This snippet code will show you how to shuffle a list in an easy and fast way.
from random import shuffle
my_list1=[1,2,3,4,5,6]
my_list2=["A","B","C","D"]
shuffle(my_list1) # [4, 6, 1, 3, 2, 5]
shuffle(my_list2) # ['A', 'D', 'B', 'C']
18. Converting String lower and upper case
This snippet code will show you how we can convert our string to lower or upper case in an easy way.
str1 ="Python Programming"
str2 ="IM A PROGRAMMER"
print(str1.upper()) #PYTHON PROGRAMMING
print(str2.lower()) #im a programmer
19. Formatting a String
This snippet Code will be helpful to formating your string. Formating in python means attaching your string with variable data. Check out the below code.
#example 1
str1 ="Python Programming"
str2 ="I'm a {}".format(str1) # I'm a Python Programming
#example 2 - another way
str1 ="Python Programming"
str2 =f"I'm a {str1}" # I'm a Python Programming
20. Find Substring
This snippet is useful when you are finding substring in a string, I will show you two ways to do that without writing a bunch of longs codes.
programmers = ["I'm an expert Python Programmer",
"I'm an expert Javascript Programmer",
"I'm a professional Python Programmer"
"I'm a beginner C++ Programmer"
]
#method 1
for p in programmers:
if p.find("Python"):
print(p)
#method 2
for p in programmers:
if "Python" in p:
print(p)
21. Printing on the Same Line
You know the print function output in every line if you had used two print functions they will print in every line. This snippet code will show you how you can print on the same line without going on the new line.
# fastest way
import sys
sys.stdout.write("Call of duty ")
sys.stdout.write("and Black Ops")
# output: Call of duty and Black Ops
#another way but only for python 3
print("Python ", end="")
print("Programming")
# output: Python Programming
22. Chunk
This snippet code will show you chunking a list and divide it into smaller parts.
def chunk(my_list, size):
return [my_list[i:i+size] for i in range(0,len(my_list), size)]
my_list = [1, 2, 3, 4, 5, 6]
chunk(my_list, 2) # [[1, 2], [3, 4], [5, 6]]
Final Thoughts:
I hope you enjoy learning these snippets. These snippets will be helpful in your programming and you can code much faster and like a pro. If you had any useful snippets in your mind, then let me know in your response. And also, you can bookmark this article. I hope it will be found helpful by you in the future. Till then, happy coding.
Check out my other articles too. Hope you will find these interesting and helpful as well.
22 Super Useful Tips and Tricks for Python Programmers
Step by Step Guide to Converting Your .py File to an .exe File
7 Ways to Earn $1000 in a Month with Programming
How to Read and Write Excel Files in Python
How to Read and Write to JSON File in Python