Python tips

Count Number of Word Appearance in a list

This tip will count the number of times the word appears in a list. check the code example below to know how it works.

from collections import Countercounter = Counter(['apple', 'mango', 'apple', 'pineapple', 'mango'])print(counter) # Counter({'apple': 2, 'mango': 2, 'pineapple': 1})

Handle speed of your Code

This tip I mostly used to handle my code speed. This tip will help you to slower your code speed.

import timetime.sleep(2) # wait for 2 sec here print("Python tips and tricks")

Breaking String

This trick will help you to break the string on basis of spaces. This is a fast and easy way to do that.

string = "Python Programming"print(string.split()) # ['Python', 'Programming']

Chain Operator Tip

This tip will help you to know what is chain operator how to use it to make your coding cleaner and faster.

num = 50result =  25 < num < 58print(result) #True

Dictionary Comprehension

This tip is helpful to understand dictionary comprehension.

dict1 = {x: x ** 2 for x in range(1, 4)}print(dict1) #{1: 1, 2: 4, 3: 9}

List Comprehension

This tip for list comprehension will help you to understand how it works and how it makes our work more easy and fast.

#normal wayx1= []for x in range(1, 10):    x1.append(x**2)print(x1) # [1, 4, 9, 16, 25, 36, 49, 64, 81]#List comprehension easy and fastx1 = [x**2 for x in range(1, 10)]print(x1) # [1, 4, 9, 16, 25, 36, 49, 64, 81]

Palindrome checking

This trick is a one-line code to check the word is palindrome or not. Now you don’t need to write a long loop to check palindrome you can do it in a fast and easy way.

w = "mom"palindrome = bool(w.find(w[: : -1]) + 1)print(palindrome)

Manipulating (append) Tuples

In Python you know that tuples are immutable that means you can’t append them to add new values. But this tip and trick will help you to append tuples and add new values to them.

tuple1 = (1, 2, 3)lst= list(tuple1)lst.append(4)lst.append(5)tuple1 = tuple(lst)print(tuple1) # (1, 2, 3, 4, 5)

Duplicate Removing from List

This tip and trick will help you to remove duplicates from a list in a fast and easy way. check out the code example below.

my_list = [10, 10, 22, 23, 27, 22, 89, 56, 25, 89]#removing duplicatesmy_list = list(set(my_list))print(my_list) # [10, 22, 23, 56, 89, 27, 25]

Calculate Execution Time

This tip will help you to measure your program running time. In simple words how much your program takes time to complete its execution.

import timedef add(a, b):    a = a + 3    b = b + 2    c = a + b    return cstartTime=time.time()add(5,4)endTime = time.time()totalTime = endTime - startTime print(totalTime) # 0.034