Top 30 Python tricks You can learn within 30 seconds

python Dec 24, 2019

I know you know Python but having some awesome cool tricks to speed up the process of getting things done won't hurt right?

So without any delay let's do it

1. Most frequent.

This method returns the most frequent item that appears in the list. Using property of Set and List

def most_frequent(list):
    return max(set(list), key = list.count)
  

numbers = [1,2,1,2,3,2,1,4,2]
most_frequent(numbers)  


2. Palindrome.

This method generates palindrome of given string. You can also use this code to reverse a list.

a =  "datadiscuss"
print("Reverse is",a[::-1])

#Reverse is ssucsidatad

3. Convert two lists into a dictionary.

The following method can be used to convert two lists into a single 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, 'c': 4, 'b': 3}


4. Check duplicates.

The following method checks whether a list has duplicate values by using the property of set() i.e. set() contains only unique elements.

def has_duplicates(lst):
    return len(lst) != len(set(lst))
    
    
x = [1,2,3,4,5,5]
y = [1,2,3,4,5]
has_duplicates(x) # True
has_duplicates(y) # False

5. Transposing a Matrix.

This python code can be used to find transpose of a given matrix.

mat = [[1, 2, 3], [4, 5, 6]]
transpose = zip(*mat)

print(set(transpose))
#[(1, 4), (2, 5), (3, 6)]

6. Swap Two Number.

Swapping two numbers without using third variable is just one line code in python(Also known as inplace swapping), If you know how this is being done inside the memory leave a comment!!!!

x, y = 10, 20
print(x, y)
 
x, y = y, x
print(x, y)
 
#1 (10, 20)
#2 (20, 10)


7. Multiple Assignment of variables.

You can assign multiple variables in a single statement using tuple unpacking property:

x, y, z = 2, 4, 8
print(x)
print(y)
print(z)
#2
#4
#8


8. Reversed Iteration.

If you want to iterate through a sequence in the reversed order, you should use keyword reversed:

for item in reversed(['u', 'v', 'w']):
  print(item)

"""
w
v
u

"""  

9. How to measure execution time of a code.

Let’s say you want to calculate the time taken to execute your code. Using a time module, You can calculate the time taken for completion of execution.

import time

startTime = time.time()

#write your code or functions calls for which you want time of execution

endTime = time.time()
totalTime = endTime - startTime

print("Total time required to execute code is= ", totalTime)

10.How to calculate memory used by an object.

Whenever you use any data structure(such as a list or dictionary or any object) to store values or records, you can check how much memory is being used this knowledge can be used to make some smart decisions regarding choice of data structure.

import sys

list1 = ['Sheetala', 'Priya', 'Prateek', 'Abhishek', 'Utkarsh']
print("size of list = ",sys.getsizeof(list1))

name = 'datadiscuss.com'
print("size of name = ",sys.getsizeof(name))

"""
size of list =  104
size of name =  61

"""

11. How to print any string n times

Often times while doing competitive programming we need to print some string so many times or n times.


n = 2; 
a ="DataDiscuss"; 
print(a * n); 

"""
DataDiscussDataDiscuss
"""

12. Checking if two words are anagrams using python:

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters present in the phrase or word exactly once.

For example

  • anagram-----—> nag a ram
  • binary ------> brainy
  • adobe ------> abode

They are anagrams

from collections import Counter 
def is_anagram(str1, str2): 
     return Counter(str1) == Counter(str2) 
print(is_anagram('adobe', 'abode')) 
  
print(is_anagram('datadiscuss  ', 'dis cuss data'))  # I added two space in data discuss

print (is_anagram("machine" , "nicheman"))

"""
True
True
False

"""

13. Create a single string from all the elements in list.

If there is multiple value present in the list and you have to join them into single string

a = ["data", "science", "bole", "to" , "data" , "discuss"] 
print(" ".join(a)) 
print("*".join(a))
print("$".join(a)) 

"""
data science bole to data discuss

data*science*bole*to*data*discuss

data$science$bole$to$data$discuss

"""

14. Get Index of Maximum and Minimum element.

How to get index of maximum and minimum value present in the python.

lst = [25,10,12,32,5]

def minIndex(lst):
  return min(range(len(lst)), key= lst.__getitem__)

def maxIndex(lst):
  return max(range(len(lst)), key= lst.__getitem__)

print(minIndex(lst))
print(maxIndex(lst))

"""
4
3

"""

15. Using "else" statement in for loop.

You can use else statement with for loop but "else" will only be executed when for loop does'nt hit break statement.

a = [1,2,3,6,4]

#case 1

for num in a:
  if num==0:
    break
else:
  print("did not break out the loop")

#case 2

for num in a:
  if num==3:
    break
else:
  print("this will not print anything") # will not be executed   

"""
did not break out the loop


"""

16. Chaining comparison operators.

Using chain comparision of operators to check the inequalities.

a = 5
b = 10
c = 3
print(c < a)
print(a < b)
print(c < a < b)

"""
True
True
True

"""

17. Use of enumerates.

Using enumerate you can find the index of elements , in the given example i will contain index.

mylist = [4,2,42]
for i, value in enumerate(mylist):
    print( i, ': ', value)
"""
0 :  4
1 :  2
2 :  42

"""

sheetala tiwari

I am passionate about Data Science and Machine Learning. I am currently building an AI community on DataDiscuss and we are committed to providing free access to education for everyone.