Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 25, 2022 03:39 pm GMT

Tips & Tricks In Python

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"print(s[::-1])

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))print(b)

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)print(b)

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_000num2 = 100_000_000_000num3 = num1+num2print(f"{num3:,}")
  • The output will be 200,000,000,000

Final Thoughts

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

Original Link: https://dev.to/raghavmri/tips-tricks-in-python-37hh

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To