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 Syntax
Place values for large numbers
If I were to ask you to tell me the number below, which one would you be able to say and understand faster?
- 5683273847
- 5,683,273,847
In Python, you can place underscores anywhere in numbers, and they will be treated as valid, which means that you can also use it for some other notation besides thirds (for whatever reason you would need to).
>>> x = 394_293_103
>>> print(x)
394293103
NOT statement
Consider the following example:
def toggle_switch(self):
if self.toggled == false:
self.toggled = true
else:
self.toggled = false
This code will certainly toggle the switch fine, but it is frankly a waste of lines. Instead of doing a conditional statement in the first place, we could simply negate the boolean using not.
def toggle_switch(self):
self.toggled = not self.toggled
bonus: test if number is not in list
if number not in list:
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
Lists, Tuples, Sequences, Iterables
Capture a particular part of an array
>>> my_list = [2,4,6,8,10,12]
>>> a, *b, c = my_list
>>> a
2
>>> b
[4, 6, 8, 10]
>>> c
12
Assign multiple variables in one line of a statement from list/tuple
my_list = [2,5,8]
a, b, c = my_list
>>> a
2
>>> b
5
>>> c
8
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
Use zip to compare elements in two lists
Instead of
>>> a = [1,5,8]
>>> b = [3,4,7]
>>> result = []
>>> for i in range(len(a)):
... result.append(a[i] if a[i]< b[i] else b[i])
...
>>> result
[1, 4, 7]
you can
>>> result = [min(i) for i in zip(a,b)]
>>> result
[1, 4, 7]
Use lambda to sort a nested array by the second element
my_list= [[1,4], [3,3], [5,7]]
my_list.sort(key= lambda x: x[1])
my_list
[[3, 3], [1, 4], [5, 7]]
Reversed python sequence
Method 1 - reversed
reversed() accepts a sequence, reverses the elements in the sequence, and finally returns the iterator.
>>> list(reversed([1, 2, 3, 4, 5]))
[5, 4, 3, 2, 1]
>>> reversed('abcd')
<reversed object at 0x7f31b2f59d68>
>>> "".join(reversed('abcd'))
'dcba'
Method 2 - slicing
Strings or lists can be reversed using slicing . To reverse a string, we simply create a slice that starts with the length of the string, and ends at index 0.
To reverse a string using slicing, write:
stringname[stringlength::-1] # method 1
or write without specifying the length of the string
stringname[::-1] # method2
Example:
>>> my_str = 'abcd'
>>> my_str[len(my_str)::-1]
'dcba'
>>> my_str[::-1]
'dcba'
>>> my_list = [1, 2, 3, 4, 5]
>>> my_list[len(my_list)::-1]
[5, 4, 3, 2, 1]
>>> my_list[::-1]
[5, 4, 3, 2, 1]
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]]
Update: The following function removes the need for importing math.
def chunk(seq, size):
return [ seq[i: i + size] for i in range(0, len(seq), size) ]
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 - 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 - Flatten Deep List
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
from collections import Counter
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 - Most frequent element in list
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]
Dictionaries
Python - How to efficiently compare two or multiple dictionaries
Above example is usable for compare dictionaries too:
from collections import Counter
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}
remap python dict keys
edited_dict = {'oldname1': 'data1', 'oldname2': 'data2', 'goodname3': 'data3'}
remaped_key = {'oldname1': 'key_1', 'oldname2': 'key_2'}
{ remaped_key[key]:edited_dict[key] for key in edited_dict if key in remaped_key }
# output
{'key_1': 'data1', 'key_2': 'data2'}
# same result:
dict((remaped_key[key], edited_dict[key]) for key, value in edited_dict.items() if key in remaped_key)
# output
{'key_1': 'data1', 'key_2': 'data2'}
edited_dict = {'oldname1': 'data1', 'oldname2': 'data2', 'goodname3': 'data3'}
remaped_key = {'oldname1': 'key_1', 'oldname2': 'key_2'}
dict((remaped_key[key], edited_dict[key]) if key in remaped_key else (key, value) for key, value in edited_dict.items())
# output
{'key_1': 'data1', 'key_2': 'data2', 'goodname3': 'data3'}
Measurement
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
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(100_000_000)
# function: f with args:"(100000000,) {}" ran in 2.49s
# -1
Python - Memory Usage
This snippet can be used to calculate memory usage to execute a particular code as a decorator to any function
from functools import wraps
import tracemalloc
def memory_size(func):
"""This decorator prints the peak memory size for the decorated function."""
@wraps(func)
def wrapper(*args, **kwargs):
tracemalloc.stop()
tracemalloc.start()
print("Tracing Status : ", tracemalloc.is_tracing())
result = func(*args, **kwargs)
first_size, first_peak = tracemalloc.get_traced_memory()
peak = first_peak/(1024*1024)
tracemalloc.stop()
print("Tracing Status : ", tracemalloc.is_tracing())
print("Peak Size in MB - ", peak)
return result
return wrapper
@memory_size
def sum_of_list(number: int) -> int:
my_list = []
for elem in range(1, number):
my_list.append(elem**2)
print(sum(my_list))
sum_of_list(10_000_000)
Strings
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 - 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
Generators
How get first n item from generator
itertools.islice (preferred method)
import itertools
list(itertools.islice(generator, n))
example:
import itertools
>>> generator = (i for i in range(10))
>>> list(itertools.islice(generator, 4))
[0, 1, 2, 3]
>>> list(itertools.islice(generator, 4))
[4, 5, 6, 7]
>>> list(itertools.islice(generator, 4))
[8, 9]
>>> list(itertools.islice(generator, 4))
[]
2 - use next function
>>> generator = (i for i in range(10))
>>> list(next(generator) for _ in range(4))
[0, 1, 2, 3]
>>> list(next(generator) for _ in range(4))
[4, 5, 6, 7]
>>> list(next(generator) for _ in range(4))
Traceback (most recent call last):
File "<stdin>", line 1, in <genexpr>
StopIteration
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: generator raised StopIteration
3 - zip function with list
>>> generator = (i for i in range(10))
>>> [x for _, x in zip(range(4), generator)]
[0, 1, 2, 3]
>>> [x for _, x in zip(range(4), generator)]
[4, 5, 6, 7]
>>> [x for _, x in zip(range(4), generator)]
[8, 9]
>>> [x for _, x in zip(range(4), generator)]
[]
4 - zip function with generator
>>> generator = (i for i in range(10))
>>> gen = (x for _, x in zip(range(4), generator))
>>> list(gen)
[0, 1, 2, 3]
>>> gen = (x for _, x in zip(range(4), generator))
>>> list(gen)
[4, 5, 6, 7]
>>> gen = (x for _, x in zip(range(4), generator))
>>> list(gen)
[8, 9]
>>> gen = (x for _, x in zip(range(4), generator))
>>> list(gen)
[]
Get every n-th item from generator
General function for every n-th element
%
is special char for modulo function. When you want get n-th element from generator, so you want element on position index started from 1, where n-th position modulo n-th number is zero
[item for index, item in enumerate(generator, start = 1) if index % n-th == 0]
example: get every second item from generator
generator = (i for i in range(100))
[item for index, item in enumerate(generator, start = 1) if index % 2 == 0]
# output
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]
example: get every third item from generator
generator = (i for i in range(100))
[item for index, item in enumerate(generator, start = 1) if index % 3 == 0]
# output
[2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 38, 41, 44, 47, 50, 53, 56, 59, 62, 65, 68, 71, 74, 77, 80, 83, 86, 89, 92, 95, 98]
example: get every 5th item from generator:
generator = (i for i in range(100))
[item for index, item in enumerate(generator, start = 1) if index % 5 == 0]
# output
[4, 9, 14, 19, 24, 29, 34, 39, 44, 49, 54, 59, 64, 69, 74, 79, 84, 89, 94, 99]
example: get every 10th item from generator
generator = (i for i in range(100))
[item for index, item in enumerate(generator, start = 1) if index % 10 == 0]
# output
[9, 19, 29, 39, 49, 59, 69, 79, 89, 99]
General Tips
Any and All
any() - return True if one of the items
of the iterable is True. If the iterable is empty, return False.
all() - return True if if all the items
of the iterable is True.
For example, in this case a one-liner is used to determine if a list has any items divisible by thirteen, using any() and list comprehension.
searchList = [9, 2, 100, 39, 28, 45, 4]
any([True if item % 13 == 0 else False for item in searchList])
# Output
True
Or, in this case, the below code uses all() to ensure that no test score is above 100 points or below 40 points (which we can assume is a minimum score), which would indicate an error somewhere.
testScores = [88, 76, 103, 98, 13, 43]
all([True if 40 <= testScore <= 100 else False for testScore in testScores])
# Output
False