Categories:

Helpful Python Snippets you can master, in seconds

Data science is a surging topic in the realm of IT and computer science. As a whole, according to Northeastern University, being a Data Scientist has been the top-ranked occupation in the U.S; the U.S. Bureau of Labor Statistics reported that the demand for data science will enable roughly 28% surge in employment through 2026. The beauty of it all, despite the huge potential, there is actually quite the shortage for qualified data scientists.

With that being known, why not learn a bit of data science and get inspired to tackle problems that may potentially lead to a possible occupation for one?

For the following code snippets, we will be utilizing Python (one of the most in-demand languages for one to learn, especially for data science).

All Unique

For this snippet, we will be utilizing a method to examine a list and see whether or not we have duplicated elements. For this, one must note that the set() will remove duplicate elements from the given list.

def all_unique(lst):
    return len(lst) == len(set(lst))

x = [1,1,2,2,2,2,3,7,9,10,8,4,2,5,6,7,1,2,2,2,1,1,1,0,0]
y = [0,1,2,3,4,5]
all_unique(x) # False
all_unique(y) # True

Anagrams

This snippet will be utilized to assess two strings and see if they are anagrams. An anagram, in case you do not know, is a word or phrase that is scrambled (ideally with the original characters).

from collections import Counter

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

anagram("potato", "oaottp") # This should come out as true

Memory

To check the memory usage of an object, you can use getsizeof() and see what it may be.

import sys

x = 100

print(sys.getsizeof(x)) #28

Byte Size

This method, in bytes, will return the length of a string.

def byte_size(string):
    return(len(string.encode('utf-8')))
    
byte_size('Good morning, coder!') # 20   

Print a string N times

To print a string N times without having to utilize a loop, you can do this.

n = 5 # You do not have to use n, it can be a different variable
s = "Mom "
print(s*n) # Mom Mom Mom Mom Mom 

Capitalize the First Letters

By utilizing the title() method, you can capitalize the first letter of every word within a given strong.

x = "my favorite animal in the world are cats"
print(x.title()) # My Favorite Animal In The World Are Cats

Snippets found on, in further detail: Towards Data Science