20 Python Snippets You Should Learn in 2021
Python is one of the most popular languages used by many in Data Science, machine learning, web development, scripting automation, etc. One of the reasons for this popularity is its simplicity and its ease of learning. If you are reading this article you are most likely already using Python or at least interested in it.
1. Check for Uniqueness in Python List
This method can be used to check if there are duplicate items in a given list.
Refer to the code below:
# Let's leverage set()
def all_unique(lst):
return len(lst) == len(set(lst))
y = [1,2,3,4,5]
print(all_unique(x))
print(all_unique(y))
2. anagram()
An anagram in the English language is a word or phrase formed by rearranging the letters of another word or phrase.
The anagram() method can be used to check if two Strings are anagrams.
from collections import Counter
def anagram(first, second):
return Counter(first) == Counter(second)
anagram("abcd3", "3acdb")
3. Memory
This can be used to check the memory usage of an object:
import sys
variable = 30
print(sys.getsizeof(variable))
4. Size in Bytes
The method shown below returns the length of the String in bytes:
def byte_size(string):
return(len(string.encode('utf-8')))
print(byte_size('?'))
print(byte_size('Hello World'))
5. Print the String n Times
This snippet can be used to display String n times without using loops:
n = 2;
s = "Programming"
print(s * n);
6. Convert the First Letters of Words to Uppercase
The snippet uses a method title() to capitalize each word in a String:
s = "programming is awesome"
print(s.title()) # Programming Is Awesome
7. Separation
This method splits the list into smaller lists of the specified size:
def chunk(list, size):
return [list[i:i+size] for i in range(0,len(list), size)]
lstA = [1,2,3,4,5,6,7,8,9,10]
lstSize = 3
chunk(lstA, lstSize)
8. Removal of False Values
So you remove the false values (False, None, 0, and ‘’) from the list using filter() method:
def compact(lst):
return list(filter(bool, lst))
compact([0, 1, False, 2, '',' ', 3, 'a', 's', 34])
9. To Count
This is done as demonstrated below:
array = [['a', 'b'], ['c', 'd'], ['e', 'f']]
transposed = zip(*array)
[print(i) for i in transposed]
10. Chain Comparison
You can do multiple comparisons with all kinds of operators in one line as shown below:
领英推荐
a = 3
print( 2 < a < 8) # True
print(1 == a < 2) # False
11. Separate With Comma
Convert a list of Strings to a single String, where each item from the list is separated by commas:
hobbies = ["singing", "soccer", "swimming"]
print("My hobbies are:") # My hobbies are:
print(", ".join(hobbies)) # singing, soccer, swimming
12. Count the Vowels
This method counts the number of vowels (“a”, “e”, “i”, “o”, “u”) found in the String:
import re
def count_vowels(value):
return len(re.findall(r'[aeiou]', value, re.IGNORECASE))
print(count_vowels('foobar')) # 3
print(count_vowels('gym')) # 0
13. Convert the First Letter of a String to Lowercase
Use the lower() method to convert the first letter of your specified String to lowercase:
def decapitalize(string):
return string[:1].lower() + string[1:]
print(decapitalize('FooBar')) # 'fooBar'
14. Anti-aliasing
The following methods flatten out a potentially deep list using recursion:
newList = [1,2]
newList.extend([3,5])
newList.append(7)
print(newList)
def spread(arg):
ret = []
for i in arg:
if isinstance(i, list):
ret.extend(i)
else:
ret.append(i)
return ret
def deep_flatten(xs):
flat_list = []
[flat_list.extend(deep_flatten(x)) for x in xs] if isinstance(xs, list) else flat_list.append(xs)
return flat_list
deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]
15. difference()
This method finds the difference between the two iterations, keeping only the values that are in the first:
def difference(a, b):
set_a = set(a)
set_b = set(b)
comparison = set_a.difference(set_b)
return list(comparison)
difference([1,2,3], [1,2,4]) # [3]
16. The Difference Between Lists
The following method returns the difference between the two lists after applying this function to each element of both lists:
def difference_by(a, b, fn):
b = set(map(fn, b))
return [item for item in a if fn(item) not in b]
from math import floor
print(difference_by([2.1, 1.2], [2.3, 3.4],floor)) # [1.2]
print(difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x'])) # [ { x: 2 } ]
17. Chained Function Call
You can call multiple functions in one line:
def add(a, b):
return a + b
def subtract(a, b):
return a - b
a, b = 4, 5
print((subtract if a > b else add)(a, b)) # 9
18. Find Duplicates
This code checks to see if there are duplicate values in the list using the fact that the set only contains unique values:
def has_duplicates(lst):
return len(lst) != len(set(lst))
x = [1,2,3,4,5,5]
y = [1,2,3,4,5]
print(has_duplicates(x)) # True
print(has_duplicates(y)) # False
19. Combine Two Dictionaries
The following method can be used to combine two dictionaries:
def merge_dictionaries(a, b):
return {**a,**b}
a = { 'x': 1, 'y': 2}
b = { 'y': 3, 'z': 4}
print(merge_dictionaries(a, b)) # {'y': 3, 'x': 1, 'z': 4}
20. Convert Two Lists to a Dictionary
Now let’s get down to converting two lists into a dictionary:
def merge_dictionaries(a, b):
return {**a,**b}
a = { 'x': 1, 'y': 2}
b = { 'y': 3, 'z': 4}
print(merge_dictionaries(a, b)) # {'y': 3, 'x': 1, 'z': 4}
def to_dictionary(keys, values):
return dict(zip(keys, values))
keys = ["a", "b", "c"]
values = [2, 3, 4]
print(to_dictionary(keys, values)) # {'a': 2, 'c': 4, 'b': 3}
Conclusion
In this article, I have covered the top 20 Python snippets which are very useful while developing any Python application. These snippets can help you save time and let you code faster. I hope you like this article. Please clap and?follow me?for more articles like this. Thank you for reading.
VP Operations at Futurescape Technologies
2 年Hi Harendra, can we connect have some opportunity to work together.