DEV Community

Sandeep
Sandeep

Posted on

4 2

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

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay