Program P
Program P
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
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.
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
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
1 n = 2
2 s ="Programming"
3
4 print(s * n) # ProgrammingProgramming
1 s = "programming is awesome"
2
3 print(s.title()) # Programming Is Awesome
7. Chunk
This method chunks a list into smaller lists of a specified size.
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 ]
9. Count by
This snippet can be used to transpose a 2D array.
1 a = 3
2 print( 2 < a < 8) # True
3 print(1 == a < 2) # False
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.
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
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') # []
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'
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_ ([ , [ ], [[ ], ], ]) [ , , , , ]
15. Difference
This method finds the difference between two iterables by keeping only the values that
are in the first one.
16. Difference by
The following method returns the difference between two lists after applying a given
function to each element of both lists.
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
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
In Python 3.5 and above, you can also do it like the following:
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)
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.
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)
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
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
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.
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]
1 a, b = -1, 14
2 a, b = b, a
3
4 print(a) # 14
5 print(b) # -1
1 d = {'a': 1, 'b': 2}
2
3 print(d.get('c', 3)) # 3
. . .
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.
https://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172 12/12