Python Tips & Tricks For Beginners

Raghav Mrituanjaya

Cover Image for Python Tips & Tricks For Beginners

In this short yet effective post,  we will discuss some of the top tips and tricks in python that might help you write your code faster 🚀

Reversing a string

s = "This is a String"

Removing duplicates from a list

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b = list(set(a))

Merging Two or More Dictionaries

a = {'a': 1, 'b': 2}
b = {'c': 3, 'd': 4}
c = {**a, **b}
  • This trick might only work for Python version >= 3.5

Converting a list of strings into a string

a = ['a', 'b', 'c']
b = ''.join(a)

Retrieving the memory size

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(sys.getsizeof(a), "Bytes")
print(sys.getsizeof(a) / 1024, "Megabytes")

Formatting Numbers

num1 = 100_000_000_000
num2 = 100_000_000_000
num3 = num1+num2
  • The output now will be 200,000,000,000

Adding Two Lists Efficiently

I tried out three famous ways to add two large lists to check which one is faster

  • Using + operator
  • Using extend() functions
  • Using for loop

For experimenting with this, I created and ran the following code

Here are the results

As you can see that using the extend() function gave me the fastest & efficient result out of the three methods

Note:- Each time I ran this code gave me different timings but the extend() was the fastest in all cases

Final Thoughts

  • This post may get updated from time to time
  • If you would like to mention any tricks kindly note them in the comment section below

P.S:- Vultr(Get a $100 credit by registering using this link) is an excellent hosting choice if you're looking for one

Buy Me A Coffee
Mind-Blowing CSS Tips and Tricks cover image

Raghav Mrituanjaya

· min read

Python Tips & Tricks For Beginners cover image


Python Tips & Tricks For Beginners

This post explains some of the coolest and best Python tricks and tips for beginners to help you cod...

Raghav Mrituanjaya

· min read

© 2023