12 Python Tips & Tricks You must know

12 Python Tips & Tricks You must know

Hello reader!

In this Blog post, I will share some useful code snippets and functions in Python. Give it a read.

Let's get started!

1. Memory

The method getsizeof can be used to retrieve the size of any object. Here's an example of the same.

import sys 
number = 100 

print(sys.getsizeof(number)) 
#output: 28

2. Swapping

The easiest way to swap values without any third variable. This is how you can do it.

a, b = 10, 20
a, b = b, a

#output:
print(a) # 20
print(b) # 10

3. Anagrams

An anagram is a play on words created by rearranging the letters of the original word to make a new word or phrase. we can sort the string values using sorted method, which does not modify the original string. Here's an example of the same.

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

res = anagram('heart', 'earth')
print(res) #True

4. Shuffle

In order to shuffle the elements of a list, shuffle method from random module can be used. Check out the implementation of the same.

from random import shuffle

my_list = [7, 23, 9, 35]
shuffle(my_list) 

print(my_list) #[35, 7, 9, 23]

5. Palindrome

A palindrome is a word, number, phrase, or other sequences of characters that reads the same backward as forward. The code snippet will check for palindrome strings.

def check_palindrome(value):
    return value == value[::-1]

res = check_palindrome('level')
print(res) #True

6. Running Time

time module can be used to calculate the actual running time amongst other methods. Refer to the implementation of the same.

import time

start_time = time.time()

num1 = 12
num2 = 15
num3 = num1 * num2
print(num3) #180

end_time = time.time()

total_time = end_time - start_time
print("Time: ", total_time)

# (Time: 0.0005068778991699219)

7. Most frequent

The max method returns the most frequently occurring element of the list.

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

nums = [7,10,50,35,10,50,29,10,10,50,4,10]

res = most_frequent(nums) 
print(res) #10

8. Fetch Vowels

Function to return all the vowels occurring in the given string.

def vowels(string):
    return [each for each in string if each in 'aeiou'] 

res = vowels('youtube')
print(res)  # ['o', 'u', 'u', 'e']

9. Convert Lists into Dictionary

zip method with dict helps to convert two lists into a dictionary. Here's an example of the same.

def convert(key, value):
    return dict(zip(key, value))

key = ["apple", "mango", "banana"]    
value = [10, 20, 30]

print(convert(key, value))
#Output: {'apple': 10, 'mango': 20, 'banana': 30}

10. Print a string k times

The following code snippet will show you how to display a string k times.

value ="Python"; 
k = 3

print(value * k) #PythonPythonPython

11. Has duplicates

The following function will return False if any duplicate is found in the given list.

def has_duplicates(my_list):
    return len(my_list) != len(set(my_list))

my_list = [7,23,45,7,10,23,93]

res = has_duplicates(my_list) 
print(res) #True

12. Chained Comparison

In order to perform multiple comparisons in a single line, a chained comparison can be used.

num1 = 27
num2 = 45

print(27 == num1 < num2) #True

That's all for this Blog folks and with that, it's a wrap! I hope you found the article useful.

I create content about Career, Blogging, Programming, and Productivity, If this is something that interests you, please share the article with your friends and connections. You can also subscribe to my newsletter to get updates every time I write something!

Thank you for reading, If you have reached so far, please like the article, It will encourage me to write more such articles. Do share your valuable suggestions, I appreciate your honest feedback!

I would strongly recommend you to Check out the YouTube video of the same and don't forget to subscribe to my Channel. I would love to connect with you at Twitter | LinkedIn.

You should definitely check out my other Blogs:

See you in my next Blog article, Take care!!

Did you find this article valuable?

Support Ayushi Rawat by becoming a sponsor. Any amount is appreciated!