In this article, we will present 30 short code snippets that you can understand and learn in 30 seconds or less.
1. Check for duplicate elements
The following method checks for duplicate elements in a given list. It uses theset()
attribute, which will remove duplicate elements from the list.
def all_unique(lst): return len(lst) == len(set(lst)) x = [1,1,2,2,3,2,3,4,5,6] y = [1,2,3,4,5] all_unique(x) # False all_unique(y) # True
2. Anagrams
Detect whether two strings are anagrams of each other (i.e., reversing the order of characters with each other)
from collections import Counter def anagram(first, second): return Counter(first) == Counter(second) anagram("abcd3", "3acdb") # True
3. Checking memory usage
The following code snippet can be used to check the memory usage of an object.
import sys variable = 30 print((variable)) # 24
4. Byte size calculation
The following methods will return the string length in bytes.
def byte_size(string): return(len(('utf-8'))) byte_size(' ') # 4 byte_size('Hello World') # 11
5. Repeat the print string N times
The following code prints a string n times without using a loop
n = 2; s ="Programming"; print(s * n); # ProgrammingProgramming
6. Initial capitalization
The following snippet uses the title()
method initializes each word within the string.
s = "programming is awesome" print(()) # Programming Is Awesome
7. Chunking
The following methods are usedrange()
Chunks the list into smaller lists of the specified size.
from math import ceil def chunk(lst, size): return list( map(lambda x: lst[x * size:x * size + size], list(range(0, ceil(len(lst) / size))))) chunk([1,2,3,4,5],2) # [[1,2],[3,4],5]
8. Compression
The following methods are usedfliter()
Remove the error value from the list (e.g:False
, None
, 0 and "")
def compact(lst): return list(filter(bool, lst)) compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ]
9. Number of intervals
The following snippet can be used to convert a two-dimensional array.
array = [['a', 'b'], ['c', 'd'], ['e', 'f']] transposed = zip(*array) print(transposed) # [('a', 'c', 'e'), ('b', 'd', 'f')]
10. Chain comparisons
The following code allows multiple comparisons in one line with various operators.
a = 3 print( 2 < a < 8) # True print(1 == a < 2) # False
This article on the super-practical 10 paragraphs Python case of the article is introduced to this, more related Python case content, please search my previous posts or continue to browse the following related articles I hope you will support me in the future more!