Helpful Python Snippets That You Can Learn in 60 Seconds or Less

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.

If you are reading this, then it is highly likely that you already use Python or at least have an interest in it.

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

Python - All Unique Elements in List


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

Python - Comparison If Two lists have same content


from collections import Counter

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


comparison([1, 2, 3, 4], [4, 3, 2, 1])         
# True
comparison("abcd3", "3acdb")       
# True
comparison("abcd3", "acdb") 
# False

Python - Memory Usage of Object


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

import sys 


variable = 30 
print(sys.getsizeof(variable))
# 28

Python - Lenght of string in bytes


This method returns the length of a string in bytes.

def byte_size(string):
    return(len(string.encode('utf-8')))
  
  
byte_size('Hello World')
# 11

Python - 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 

Python - chunk a list into smaller lists of a specified size


This method uses range() to chunk a list into smaller lists of a 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]]

Python - Compact


This method removes falsy values (False, None, 0 and “) from a list by using python filter() function.

def compact(lst):
    return list(filter(bool, lst))
  
  
compact([0, 1, False, 2, '', 3, 'a', 's', 34])
# [1, 2, 3, 'a', 's', 34]

Python - Transpose a 2D Array


This snippet can be used to transpose a 2D array.

array = [['a', 'b'], ['c', 'd'], ['e', 'f']]
transposed = zip(*array)

print(list(transposed))
# [('a', 'c', 'e'), ('b', 'd', 'f')]

Python - Chained comparison


You can do multiple comparisons with all kinds of operators in a single line.

a = 3
print( 2 < a < 8)
# True
print(1 == a < 2)
# False

Python - Turn a list of strings into a single string


This snippet can be used to turn a list of strings into a single string with each element from the list separated by commas.

hobbies = ["basketball", "football", "swimming"]

print("My hobbies are: " + ", ".join(hobbies))
# My hobbies are: basketball, football, swimming

print(", ".join(hobbies))
# basketball, football, swimming

Python - How Count Vowels


This method counts the number of vowels (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) found in a string.

import re

def count_vowels(str):
    return len(re.findall(r'[aeiou]', str, re.IGNORECASE))

count_vowels('foobar')
# 3

Python - Flatten


The following methods flatten a potentially deep list using recursion.

Method 1:

def flatten(lst):
    return sum( ([x] if not isinstance(x, list) else flatten(x) 
                 for x in lst), [] )


lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
flatten(lst)
# [1, 2, 3, 4, 5, 6, 7, 8]

Method 2:

This method shows a solution using Python generators.

def flatten(lst):
     for x in lst:
         if isinstance(x, list):
             for x in flatten(x):
                 yield x
         else:
             yield x


lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
print(list(flatten(lst)))
# [1, 2, 3, 4, 5, 6, 7, 8]

source:

https://rosettacode.org/wiki/Flatten_a_list
https://pythontips.com/2013/09/29/the-python-yield-keyword-explained/

Python - Difference


This method finds the difference between two iterables by keeping only the values that are in the first one.

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]

Python - Difference by


The following method returns the difference between two lists after applying a given 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
difference_by([2.1, 1.2], [2.3, 3.4],floor)
# [1.2]

difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x'])
# [{'x': 2}]

Python - Check A list has a duplicate values


The following method checks whether a list has duplicate values by using the fact that set() contains only unique elements.

def has_duplicates(lst):
    return len(lst) != len(set(lst))
    

x = [1,2,3,4,5,5]
has_duplicates(x)
# True

y = [1,2,3,4,5]
has_duplicates(y)
# False

Python - How to efficiently compare two or multiple unordered lists


def compare_hashable_objects(*args):
    for arg in args:
        if Counter(args[0]) == Counter(arg):
            pass
        else:
            return False
    return True


one = [33, 22, 11, 44, 55]
two = [22, 11, 44, 55, 33]

compare_hashable_objects(one, two)
# True

Python - How to efficiently compare two or multiple dictionaries


Above example is usable for compare dictionaries too:

def compare_hashable_objects(*args):
    for arg in args:
        if Counter(args[0]) == Counter(arg):
            pass
        else:
            return False
    return True
   

one = {1: 'one', 2: "two", 3: "three"}
two = {2: "two", 3: "three", 1: 'one'}
   
compare_hashable_objects(one, two)
# True

Python - Merge two dictionaries


The following method can be used to merge 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))
# {'x': 1, 'y': 3, 'z': 4}

Python - Merge N dictionaries


The following method merge multiple dictionaries to one big:

def merge_dictionaries(*args):
    sum_of_dict = {}
    for item in args:
        sum_of_dict.update(item)
    return sum_of_dict


a = {'x': 1, 'y': 2}
b = {'y': 3, 'z': 4}
c = {'a': 7, 'b': 6, 'c': 5, 'd': 4}
print(merge_dictionaries(a, b, c))
# {'x': 1, 'y': 3, 'z': 4, 'a': 7, 'b': 6, 'c': 5, 'd': 4}

Python - Merge N dictionaries with dictionary comprehension


You can use a dictinary comprehension for previous example of merge multiple dictionaries.

def merge_dictionaries(*args):
    return {key: value for dictionary in args for key, value in dictionary.items()}


a = {'x': 1, 'y': 2}
b = {'y': 3, 'z': 4}
c = {'a': 7, 'b': 6, 'c': 5, 'd': 4}
print(merge_dictionaries(a, b, c))
# {'x': 1, 'y': 3, 'z': 4, 'a': 7, 'b': 6, 'c': 5, 'd': 4}

Or you can use this formula direct in your programs:

a = {'x': 1, 'y': 2}
b = {'y': 3, 'z': 4}
c = {'a': 7, 'b': 6, 'c': 5, 'd': 4}
print({**a, **b, **c})
# {'x': 1, 'y': 3, 'z': 4, 'a': 7, 'b': 6, 'c': 5, 'd': 4}

Python - Convert two lists into a dictionary


The following method can be used to convert two lists into a dictionary.

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, 'b': 3, 'c': 4}

Pyton - Time Spent


This snippet can be used to calculate the time it takes to execute a particular code as a decorator to any function

from functools import wraps
import time

def timing(func):
    """This decorator prints the execution time for the decorated function."""
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f'function: {func.__name__} with args:"{args} {kwargs}" ran in {round(end - start, 2)}s')
        return result
    return wrapper

@timing
def f(a):
    for _ in range(a):
        i = 0
    return -1

f(100000000)
# function: f with args:"(100000000,) {}" ran in 2.49s
# -1

Python - Most frequent element in list


  1. Preferred method: use Counter class from collections
from collections import Counter

def most_frequent(list):
    counter = Counter(list)
    return max(counter.items(), key = lambda x: x[1])[0]


original_list = [1,1,1,1,1,2,2,2,2,3,3,4,5,5]
print(most_frequent(original_list))
# 1

Python - Randomize order of the elements in list


This algorithm randomizes the order of the elements in a list by implementing the Fisher-Yates algorithm to do the ordering in the new list.

from copy import deepcopy
from random import randint

def shuffle(lst):
    temp_lst = deepcopy(lst)
    m = len(temp_lst)
    while (m):
        m -= 1
        i = randint(0, m)
        temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m]
    return temp_lst

  
foo = [1,2,3]
shuffle(foo)
# [3, 1, 2]
Share Comments
comments powered by Disqus