DEV Community

loading...

5 Python Code Snippets For You

RebelX
The Rebel NeXtdoor | Python Developer | Developer Advocate | Ehub247, TechO’clock and iDer Ambassador | Technical Writer
・1 min read

Python represents one of the most popular languages that many people use it in data science and machine learning, web development, scripting, automation, etc.
Part of the reason for this popularity is its simplicity and easiness to learn it.

In this article, we will briefly see 30 short code snippets that you can understand and learn in 30 seconds or less.

All unique
The following method checks whether the given list has duplicate elements. It uses the property of set() which removes 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
Enter fullscreen mode Exit fullscreen mode

Anagrams
This method can be used to check if two strings are anagrams. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

from collections import Counter

def anagram(first, second):
    return Counter(first) == Counter(second)


anagram("abcd3", "3acdb") # True
Enter fullscreen mode Exit fullscreen mode

Memory
This snippet can be used to check the memory usage of an object.

import sys 

variable = 30 
print(sys.getsizeof(variable))
Enter fullscreen mode Exit fullscreen mode

Byte size
This method returns the length of a string in bytes.

def byte_size(string):
    return(len(string.encode('utf-8')))


byte_size('😀')
byte_size('Hello World')
Enter fullscreen mode Exit fullscreen mode

Print a string N times
This snippet can be used to print a string n times without having to use loops to do it.

n = 2
s ="Programming"

print(s * n) # ProgrammingProgramming
Enter fullscreen mode Exit fullscreen mode

Discussion (0)