Home / News / 10 useful Python fragments to help you work

10 useful Python fragments to help you work

29 fragments implemented in Python that will help write code at the speed of Flesh!

Python represents one of the most popular languages many use in data science and machine learning, web development, scripting, automation, etc. One reason for this popularity is simplicity and ease of mastering.

If you ‘re reading this, you ‘re likely already using Python or at least interested in it.

In the article, we ‘ll briefly look at 29 short code snippets that you can understand and master incredibly quickly. Went!

  1. Check for uniqueness
    The following method checks whether there are duplicate items in this list. It uses the set () property, which removes duplicate items 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.Anagram
This method can be used to check whether two lines are anagrams. An anagram is a word or phrase formed by permuting the letters of another word or phrase, usually using all the original letters exactly once:

from collections import Counter

def anagram(first, second):

return Counter(first) == Counter(second)

anagram(“abcd3”, “3acdb”) # True

3. Memory
And this can be used to check the use of memory by an object:

import sys

variable = 30

print(sys.getsizeof(variable)) # 24

4.Size in bytes
The method returns the length of the string in bytes:

def byte_size(string):

return(len(string.encode(‘utf-8’)))

byte_size(‘😀’) # 4

byte_size(‘Hello World’) # 11

5.Display the line N times
This fragment can be used to output the string n times without having to use cycles:

n = 2;

s = “Programming”;

print(s * n); # ProgrammingProgramming

6.Display the line N times
This fragment can be used to output the string n times without having to use cycles:

s = “programming is awesome”

print(s.title()) # Programming Is Awesome

7.Division
This method divides 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)]

8.Delete false values
So you remove false values (False, None, 0, and “) from the list using filter ():

def compact(lst):

return list(filter(bool, lst))

compact([0, 1, False, 2, ”, 3, ‘a’, ‘s’, 34]) # [ 1, 2, 3, ‘a’, ‘s’, 34 ]

9.Calculation
The following code can be used to transpose a 2D array:

array = [[‘a’, ‘b’], [‘c’, ‘d’], [‘e’, ‘f’]]

transposed = zip(*array)

print(transposed) # [(‘a’, ‘c’, ‘e’), (‘b’, ‘d’, ‘f’)]

10.Chain Comparison
You can make several comparisons with all kinds of statements in one line:

a = 3

print( 2 < a < 8) # True

print(1 == a < 2) # False

About IT

Check Also

operating systems : how did everything start?

Interested in the history of operating systems development? Super! You will learn why “Apple” is …

Leave a Reply

Your email address will not be published. Required fields are marked *