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

Image of Timescale

πŸš€ pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applicationsβ€”without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post β†’

Top comments (0)

Image of Docusign

πŸ› οΈ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more