Tips & Tricks for Python

sandeepk27

Sandeep

Posted on April 5, 2022

Tips & Tricks for Python

1. Memory

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

import sys
number = 100
print(sys.getsizeof(number))


# Output: 28
Enter fullscreen mode Exit fullscreen mode

2. Swapping

This is the easiest way to swap values without using any third variable.

a,b = 5,10
a,b = b,a
print(a)
print(b)


# Output:
# 10
# 5
Enter fullscreen mode Exit fullscreen mode

*3. Anagrams *

An anagram is a play on words created by rearranging the letters of the original word to make a new phrase or word.

We can sort the string values using sorted method, which does not modify the original string.

def anagram(first, second):
    return sorted(first)=
sorted(second)
res - anagram( 'heart', 'earth')
print(res) #True
Enter fullscreen mode Exit fullscreen mode

4. Shuffle

Shuttle method from random module, in order to shuffle the elements of a list.

from random import shuffle
my_list = [7, 23, 9, 35]
shuffle(my list)
print(my_list) #[35, 7, 9, 23]
Enter fullscreen mode Exit fullscreen mode

5. Palindrome

A palindrome is a word, number, phrase or other sequences of characters that reads the same backward as forward.

from random import shuffle
my_list = [7, 23, 9, 35]
shuffle(my list)
print(my_list) #[35, 7, 9, 23]
Enter fullscreen mode Exit fullscreen mode
  1. Running Time

time module can be used to calculate the actual running time amongst other methods.

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)
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
sandeepk27
Sandeep

Posted on April 5, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Tips & Tricks for Python
beginners Tips & Tricks for Python

April 5, 2022