3/27/2020 30 Helpful Python Snippets That You Can Learn in 30 Seconds or Less
30 Helpful Python Snippets That You Can Learn in
30 Seconds or Less
Fatos Morina
Sep 7, 2019 · 4 min read
Photo by Jantine Doornbos on Unsplash
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.
https://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172 1/12
3/27/2020 30 Helpful Python Snippets That You Can Learn in 30 Seconds or Less
In this article, we will briefly see 30 short code snippets that you can understand and
learn in 30 seconds or less.
1. 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.
1 def all_unique(lst):
2 return len(lst) == len(set(lst))
3
4
5 x = [1,1,2,2,3,2,3,4,5,6]
6 y = [1,2,3,4,5]
7 all_unique(x) # False
8 all_unique(y) # True
all_unique.py hosted with ❤ by GitHub view raw
2. 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.
1 from collections import Counter
2
3 def anagram(first, second):
4 return Counter(first) == Counter(second)
5
6
7 anagram("abcd3", "3acdb") # True
anagram.py hosted with ❤ by GitHub view raw
3. Memory
This snippet can be used to check the memory usage of an object.
1 import sys
2
3 variable = 30
4 print(sys.getsizeof(variable)) # 24
memory.py hosted with ❤ by GitHub view raw
https://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172 2/12
3/27/2020 30 Helpful Python Snippets That You Can Learn in 30 Seconds or Less
4. Byte size
This method returns the length of a string in bytes.
1 def byte_size(string):
2 return(len(string.encode('utf-8')))
3
4
5 byte_size('😀') # 4
6 byte_size('Hello World') # 11
byte_size.py hosted with ❤ by GitHub view raw
5. Print a string N times
This snippet can be used to print a string n times without having to use loops to do it.
1 n = 2
2 s ="Programming"
3
4 print(s * n) # ProgrammingProgramming
print.py hosted with ❤ by GitHub view raw
6. Capitalize first letters
This snippet simply uses the method title() to capitalize first letters of every word in a
string.
1 s = "programming is awesome"
2
3 print(s.title()) # Programming Is Awesome
capitalize_words.py hosted with ❤ by GitHub view raw
7. Chunk
This method chunks a list into smaller lists of a specified size.
1 def chunk(list, size):
2 return [list[i:i+size] for i in range(0,len(list), size)]
chunk.py hosted with ❤ by GitHub view raw
https://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172 3/12
3/27/2020 30 Helpful Python Snippets That You Can Learn in 30 Seconds or Less
8. Compact
This method removes falsy values (False, None, 0 and “”) from a list by using filter().
1 def compact(lst):
2 return list(filter(None, lst))
3
4
5 compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ]
compact.py hosted with ❤ by GitHub view raw
9. Count by
This snippet can be used to transpose a 2D array.
1 array = [['a', 'b'], ['c', 'd'], ['e', 'f']]
2 transposed = zip(*array)
3 print(transposed) # [('a', 'c', 'e'), ('b', 'd', 'f')]
transpose.py hosted with ❤ by GitHub view raw
10. Chained comparison
You can do multiple comparisons with all kinds of operators in a single line.
1 a = 3
2 print( 2 < a < 8) # True
3 print(1 == a < 2) # False
comparisons.py hosted with ❤ by GitHub view raw
11. Comma-separated
This snippet can be used to turn a list of strings into a single string with each element
from the list separated by commas.
1 hobbies = ["basketball", "football", "swimming"]
2
3 print("My hobbies are:") # My hobbies are:
4 print(", ".join(hobbies)) # basketball, football, swimming
comma_separated.py hosted with ❤ by GitHub view raw
https://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172 4/12
3/27/2020 30 Helpful Python Snippets That You Can Learn in 30 Seconds or Less
12. Get vowels
This method gets vowels (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) found in a string.
1 def get_vowels(string):
2 return [each for each in string if each in 'aeiou']
3
4
5 get_vowels('foobar') # ['o', 'o', 'a']
6 get_vowels('gym') # []
get_vowels.py hosted with ❤ by GitHub view raw
13. Decapitalize
This method can be used to turn the first letter of the given string into lowercase.
1 def decapitalize(str):
2 return str[:1].lower() + str[1:]
3
4
5 decapitalize('FooBar') # 'fooBar'
6 decapitalize('FooBar') # 'fooBar'
decapitalize.py hosted with ❤ by GitHub view raw
14. Flatten
The following methods flatten a potentially deep list using recursion.
1 def spread(arg):
2 ret = []
3 for i in arg:
4 if isinstance(i, list):
5 ret.extend(i)
6 else:
7 ret.append(i)
8 return ret
9
10 def deep_flatten(xs):
11 flat_list = []
12 [flat_list.extend(deep_flatten(x)) for x in xs] if isinstance(xs, list) else flat_list.appe
13 return flat_list
14
15
16 deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]
https://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172 5/12
3/27/2020 30 Helpful Python Snippets That You Can Learn in 30 Seconds or Less
p_ ([ , [ ], [[ ], ], ]) [ , , , , ]
flatten.py hosted with ❤ by GitHub view raw
15. Difference
This method finds the difference between two iterables by keeping only the values that
are in the first one.
1 def difference(a, b):
2 set_a = set(a)
3 set_b = set(b)
4 comparison = set_a.difference(set_b)
5 return list(comparison)
6
7
8 difference([1,2,3], [1,2,4]) # [3]
differences.py hosted with ❤ by GitHub view raw
16. Difference by
The following method returns the difference between two lists after applying a given
function to each element of both lists.
1 def difference_by(a, b, fn):
2 b = set(map(fn, b))
3 return [item for item in a if fn(item) not in b]
4
5
6 from math import floor
7 difference_by([2.1, 1.2], [2.3, 3.4], floor) # [1.2]
8 difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x']) # [ { x: 2 } ]
difference_by.py hosted with ❤ by GitHub view raw
17. Chained function call
You can call multiple functions inside a single line.
1 def add(a, b):
2 return a + b
3
4 def subtract(a, b):
5 return a - b
https://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172 6/12
3/27/2020 30 Helpful Python Snippets That You Can Learn in 30 Seconds or Less
6
7 a, b = 4, 5
8 print((subtract if a > b else add)(a, b)) # 9
chained.py hosted with ❤ by GitHub view raw
18. Has duplicates
The following method checks whether a list has duplicate values by using the fact that
set() contains only unique elements.
1 def has_duplicates(lst):
2 return len(lst) != len(set(lst))
3
4
5 x = [1,2,3,4,5,5]
6 y = [1,2,3,4,5]
7 has_duplicates(x) # True
8 has_duplicates(y) # False
has_duplicates.py hosted with ❤ by GitHub view raw
19. Merge two dictionaries
The following method can be used to merge two dictionaries.
1 def merge_two_dicts(a, b):
2 c = a.copy() # make a copy of a
3 c.update(b) # modify keys and values of a with the ones from b
4 return c
5
6
7 a = { 'x': 1, 'y': 2}
8 b = { 'y': 3, 'z': 4}
9 print(merge_two_dicts(a, b)) # {'y': 3, 'x': 1, 'z': 4}
merge.py hosted with ❤ by GitHub view raw
In Python 3.5 and above, you can also do it like the following:
1 def merge_dictionaries(a, b):
2 return {**a, **b}
3
4
5 a = { 'x': 1, 'y': 2}
6 b = { 'y': 3, 'z': 4}
https://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172 7/12
3/27/2020 30 Helpful Python Snippets That You Can Learn in 30 Seconds or Less
6 b { y : 3, : }
7 print(merge_dictionaries(a, b)) # {'y': 3, 'x': 1, 'z': 4}
merge_dictionaries.py hosted with ❤ by GitHub view raw
20. Convert two lists into a dictionary
The following method can be used to convert two lists into a dictionary.
1 def to_dictionary(keys, values):
2 return dict(zip(keys, values))
3
4
5 keys = ["a", "b", "c"]
6 values = [2, 3, 4]
7 print(to_dictionary(keys, values)) # {'a': 2, 'c': 4, 'b': 3}
to_dictionary.py hosted with ❤ by GitHub view raw
21. Use enumerate
This snippet shows that you can use enumerate to get both the values and the indexes of
lists.
1 list = ["a", "b", "c", "d"]
2 for index, element in enumerate(list):
3 print("Value", element, "Index ", index, )
4 # ('Value', 'a', 'Index ', 0)
5 # ('Value', 'b', 'Index ', 1)
6 #('Value', 'c', 'Index ', 2)
7 # ('Value', 'd', 'Index ', 3)
enumerate.py hosted with ❤ by GitHub view raw
22. Time spent
This snippet can be used to calculate the time it takes to execute a particular code.
1 import time
2
3 start_time = time.time()
4
5 a = 1
6 b = 2
7 c = a + b
8 print(c) #3
https://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172 8/12
3/27/2020 30 Helpful Python Snippets That You Can Learn in 30 Seconds or Less
9
10 end_time = time.time()
11 total_time = end_time - start_time
12 print("Time: ", total_time)
13
14 # ('Time: ', 1.1205673217773438e-05)
time_taken.py hosted with ❤ by GitHub view raw
23. Try else
You can have an else clause as part of a try/except block, which is executed if no
exception is thrown.
1 try:
2 2*3
3 except TypeError:
4 print("An exception was raised")
5 else:
6 print("Thank God, no exceptions were raised.")
7
8 #Thank God, no exceptions were raised.
try_else.py hosted with ❤ by GitHub view raw
24. Most frequent
This method returns the most frequent element that appears in a list.
1 def most_frequent(list):
2 return max(set(list), key = list.count)
3
4
5 numbers = [1,2,1,2,3,2,1,4,2]
6 most_frequent(numbers)
most_frequent.py hosted with ❤ by GitHub view raw
25. Palindrome
This method checks whether a given string is a palindrome.
1 def palindrome(a):
2 return a == a[::-1]
3
4
https://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172 9/12
3/27/2020 30 Helpful Python Snippets That You Can Learn in 30 Seconds or Less
4
5 palindrome('mom') # True
palindrome.py hosted with ❤ by GitHub view raw
26. Calculator without if-else
The following snippet shows how you can write a simple calculator without the need to
use if-else conditions.
1 import operator
2 action = {
3 "+": operator.add,
4 "-": operator.sub,
5 "/": operator.truediv,
6 "*": operator.mul,
7 "**": pow
8 }
9 print(action['-'](50, 25)) # 25
operator.py hosted with ❤ by GitHub view raw
27. Shuffle
This snippet can be used to randomize the order of the elements in a list. Note that
shuffle works in place, and returns None.
1 from random import shuffle
2
3 foo = [1, 2, 3, 4]
4 shuffle(foo)
5 print(foo) # [1, 4, 3, 2] , foo = [1, 2, 3, 4]
shuffle.py hosted with ❤ by GitHub view raw
28. Spread
This method flattens a list similarly like [].concat(…arr) in JavaScript.
1 def spread(arg):
2 ret = []
3 for i in arg:
4 if isinstance(i, list):
5 ret.extend(i)
6 else:
7 ret append(i)
https://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172 10/12
3/27/2020 30 Helpful Python Snippets That You Can Learn in 30 Seconds or Less
7 ret.append(i)
8 return ret
9
10
11 spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]
spread.py hosted with ❤ by GitHub view raw
29. Swap values
A really quick way for swapping two variables without having to use an additional one.
1 a, b = -1, 14
2 a, b = b, a
3
4 print(a) # 14
5 print(b) # -1
swap.py hosted with ❤ by GitHub view raw
30. Get default value for missing keys
This snippet shows how you can get a default value in case a key you are looking for is
not included in the dictionary.
1 d = {'a': 1, 'b': 2}
2
3 print(d.get('c', 3)) # 3
missing_key.py hosted with ❤ by GitHub view raw
. . .
This was a short list of snippets that you may find useful in your everyday work. It was
highly based on this GitHub repository in which you can find many other useful code
snippets both in Python and other languages and technologies.
. . .
Thank you for taking the time to read. Please do not forget to give it a clap 👏
(you can also clap multiple times) and comment down below 👇. I would really
https://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172 11/12
3/27/2020 30 Helpful Python Snippets That You Can Learn in 30 Seconds or Less
appreciate it.
Arti cial Intelligence Technology Productivity Education Programming
About Help Legal
https://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172 12/12