[Python] 25 useful Python snippets to help you with your daily work

Keywords: Python Lambda Programming

Introduction

Python is a general advanced programming language.There are many things you can do with it, such as developing desktop GUI applications, Web sites, Web applications, and so on.
Python also allows developers to focus on the core functionality of the application by handling common programming tasks.In addition, the simple syntax rules of the Python language further simplify the readability of the code base and the maintainability of the application.

The advantages of Python over other programming languages are:

  • Compatible with major platforms and operating systems;
  • There are many open source frameworks and tools;
  • Code is readable and maintainable;
  • Robust standard library;
  • Standard Test Driven Development

In this article, I will introduce 25 short and useful code snippets that can help you accomplish your daily tasks.

Reference English: 25 Useful Python Snippets to Help in Your Day-to-Day Work

1. Exchange values between two variables

In other languages, to exchange values between two variables instead of using a third variable, we either use an arithmetic operator or use Bitwise XOR.In Python, it's much simpler, as shown below.

a = 5
b = 10                   
a,b = b,a
print(a) # 10
print(b) # 5

2. Check if a given number is even

If the given number is even, the following function returns Ture, otherwise it returns False.

def is_even(num):
    return num % 2 == 0
    
is_even(10) # True

3. Split multi-line strings into line lists

The following functions can be used to split a multiline string into a list of rows.

def split_lines(s):
    return s.split('\n')
split_lines('50\n python\n snippets') # ['50', ' python', ' snippets']

4. Memory used to find objects

The sys module of the standard library provides the getsizeof() function.This function accepts an object, calls the object's sizeof() method, and returns the result, which makes the object inspectable.

import sys
print(sys.getsizeof(5)) # 28
print(sys.getsizeof("Python")) # 55

5. Invert String

The Python string library does not support built-in reverse() as other Python containers, such as lists.There are many ways to invert strings, the simplest of which is to use the slicing operator.

language = "python"
reversed_language = language[::-1]
print(reversed_language) # nohtyp

6. Print string n times

Without loops, it is easy to print a string n times, as shown below.

def repeat(string, n):
    return (string * n)
    
repeat('python', 3) # pythonpythonpython

7. Check if the string is palindrome

The following functions check whether a string is a palindrome.

def palindrome(string):
    return string == string[::-1]
    
palindrome('python') # False

8. Merge the list of strings into a single string

The following code snippet combines a list of strings into a single string.

strings = ['50', 'python', 'snippets']
print(','.join(strings)) # 50,python,snippets

9. Find the first element of the list

This function returns the first element of the passed list.

def head(list):
  return list[0]
  
print(head([1, 2, 3, 4, 5])) # 1

10. Find elements that exist in either of the two lists

This function returns each element in either of the two lists.

def union(a,b):
    return list(set(a + b))
union([1, 2, 3, 4, 5], [6, 2, 8, 1, 4]) # [1,2,3,4,5,6,8]

11. Find all unique elements in a given list

This function returns the unique element that exists in a given list.

def unique_elements(numbers):
    return list(set(numbers))
    
unique_elements([1, 2, 3, 2, 4]) # [1, 2, 3, 4]

12. Average a set of numbers

This function returns the average of two or more numbers in the list.

def average(*args):
  return sum(args, 0.0) / len(args)
  
average(5, 8, 2) # 5.0

13. Check that the list contains all unique values

This function checks if all elements in the list are unique.

def unique(list):
    if len(list)==len(set(list)):
        print("All elements are unique")
    else:
        print("List has duplicates")
        
unique([1,2,3,4,5]) # All elements are unique

14. Track the frequency of elements in the list

The Python counter tracks the frequency of each element in the container.Counter() returns a dictionary with elements as keys and values based on their frequency of occurrence.

from collections import Counter
list = [1, 2, 3, 2, 4, 3, 2, 3]
count = Counter(list)
print(count) # {2: 3, 3: 3, 1: 1, 4: 1}

15. Find the most common elements in the list

This function returns the most frequently occurring element in the list.

def most_frequent(list):
    return max(set(list), key = list.count)
    
numbers = [1, 2, 3, 2, 4, 3, 1, 3]
most_frequent(numbers) # 3

16. Convert angle to radian

The following functions convert angles to radians.

import math
def degrees_to_radians(deg):
    return (deg * math.pi) / 180.0 
    
degrees_to_radians(90) # 1.5707963267948966

17. Calculate the time required to execute a piece of code

The following code snippet calculates the time required to execute a piece of code.

import time
start_time = time.time()
a,b = 5,10
c = a+b
end_time = time.time()
time_taken = (end_time- start_time)*(10**6)
print("Time taken in micro_seconds:", time_taken) # Time taken in micro_seconds: 39.577484130859375

18. Find the greatest common divisor of a list of numbers

This function calculates the greatest common divisor in the list of numbers.

from functools import reduce
import math
def gcd(numbers):
    return reduce(math.gcd, numbers)
gcd([24,108,90]) # 6

19. Find unique characters in a string

This snippet can be used to find all unique characters in a string.

string = "abcbcabdb"   
unique = set(string)
new_string = ''.join(unique)
print(new_string) # abcd

20. Use lambda functions

Lambda is an anonymous function and can only save one expression.

x = lambda a, b, c : a + b + c
print(x(5, 10, 20)) # 35

21. Use mapping functions

This function returns a list of results after applying the given function to each item (list, tuple, and so on) of a given iteration.

def multiply(n): 
    return n * n 
    
list = (1, 2, 3) 
result = map(multiply, list) 
print(list(result)) # {1, 4, 9}

22. Using filter functions

This function filters a given sequence through a function to test whether each element in the sequence is true.

arr = [1, 2, 3, 4, 5]
arr = list(filter(lambda x : x%2 == 0, arr))
print (arr) # [2, 4]

23. Use list resolution

list comprehensions provide us with an easy way to create lists based on some iterations.During the creation process, elements from Iteratives can be conditionally included in the new list and converted as needed.

numbers = [1, 2, 3]
squares = [number**2 for number in numbers]
print(squares) # [1, 4, 9]

24. Using the slice operator

Slicing is used to extract consecutive element sequences or subsequences from a given sequence.The following functions connect the results of two slicing operations.First, we'll slice the list from index d to the end, then from the beginning to index d.

def rotate(arr, d):
    return arr[d:] + arr[:d]
    
if __name__ == '__main__':
    arr = [1, 2, 3, 4, 5]
    arr = rotate(arr, 2)
    print (arr) # [3, 4, 5, 1, 2]

25. Use function chain calls

The final code snippet is used to call multiple functions from one line and compute the results.

def add(a, b):
    return a + b
def subtract(a, b):
    return a - b
a, b = 5, 10
print((subtract if a > b else add)(a, b)) # 15
If you learn to sail against the water, if you don't advance, you will go back.
Published 500 original articles, won 1259, visited 180,000+
Private letter follow

Posted by Goafer on Fri, 07 Feb 2020 22:20:58 -0800