Skip to content

Top 10 Python Tricks That Every Programmer Needs To Know

NameCheap affiliate ad

Simple but effective python tricks that will blow your mind and its helpful for beginners

Pytho Tricks for web developers

Python’s compactness can make a developer’s life much easier when creating lines and lines of code. However, there are several lesser-known Python methods that will astound you with their incredible potential.

In today’s article, I’ll go through 10 Python tricks and tips that will help beginners write more concise code. Knowing these tips and tricks will undoubtedly save you time.

Without further ado. Let’s get started!!

List of Top 10 Python tricks

Here is a list of the top 10 python tricks that are amazing and will help you in getting started with python programming

list of top 10 python tricks

1. Determine the distinctions between the two Lists.

This is one of the best python tricks. Let’s say you have the following two lists.

Example

list1 = ['Arif', 'Adnan', 'Amar', 'Alia', 'Arnav']
list2 = ['Adnan', 'Anil', 'Arif']

If you want to make a third list from the first list that contains items that aren’t in the second list. So you want something like list3 = [‘Alia’, ‘Arnav’]

Let’s see how we can do it without looping and verifying. To obtain all of the differences, use the set’s symmetric_difference operator.

Example

list1 = ['Arif', 'Adnan', 'Amar', 'Alia', 'Arnav']
list2 = ['Adnan', 'Anil', 'Arif']

set1 = set(list1)
set2 = set(list2)

list3 = list(set1.symmetric_difference(set2))
print(list3)

Output

list3 = [ 'Alia', 'Arnav']

2. The zip() function

When working with lists and dictionaries, the zip() function in Python can be extremely useful. It is used to join together multiple lists of the same length.

Example

colour = [“red”, “yellow”, “green”]
fruits = [‘apple’, ‘banana’, ‘mango’]
for colour, fruits in zip(colour, fruits):
print(colour, fruits)

Outptut

red apple
yellow banana
green mango

The zip() function can also be used to join two lists together to form a dictionary. This approach is quite useful for grouping data from a list.

Example

students = [“Amer”, “Kiran”, “Anushka”]
marks = [78, 92, 95]
dictionary = dict(zip(students, marks))
print(dictionary

Output

{‘Amer’: 78, ‘Kiran’: 92, ‘Anushka’: 95}

3. Splitting a string

The Python split() method makes it simple to separate a string’s component elements into a list. The string operations will be easier as a result!

Example

string = “hello world”
string.split()

Output

[‘hello’, ‘world’]

4. Time elapsed using python

Let’s imagine you want to determine how long it will take your code to execute. So, you can determine how long it will take for your code to run by using a time module.

Example

import time

startTime = time.time()

# write your code or functions calls

endTime = time.time()
totalTime = endTime - startTime

print("Total time required to execute code is= ", totalTime)

5.  Calculate memory

whenever you use a data structure to hold values or records (such as a list, dictionary, or object).
It is a good idea to keep track of how much memory your data structure consumes.

To obtain the memory occupied by built-in objects, use the sys.getsizeof function defined in the sys module. sys.getsizeof(object[, default]) returns an object’s size in bytes.

Example

import sys

list1 = ['Scott', 'Eric', 'Kelly', 'Emma', 'Smith']
print("size of list = ",sys.getsizeof(list1))

name = 'pynative.com'
print("size of name = ",sys.getsizeof(name))

Output

('size of list = ', 112)
('size of name = ', 49)

Note:-It should be noted that sys.getsizeof does not return the right value for third-party or user-defined objects.

6. Walrus operator

The Walrus or:= operator is a new addition to Python 3.8. It is an assignment operator that allows you to assign values to variables within expressions like as conditional statements, loops, and so on.

If we want to check and print the length of a list:

Example

Mylist = [4,5,6]
if(l := len(mylist) > 5)
print(l)

Output

6

7. Merging two dictionaries

This incredible method will allow you to merge two dictionaries with just one line of code. Simply put ** in front of the names of the two dictionaries, as shown below, to combine them into a single dictionary:

Example

d1 = {“a”: 100, “b”:200}
d2 = {“c”: 300, “d”:400}
d3 = {**d1, **d2}
print(d3)

Output

{‘a’: 100, ‘b’: 200, ‘c’: 300, ‘d’: 400}

8. Allocating numerous list values to a variable

You can use the following technique to allocate some specified values from a list to a variable and all the other values to another variable in a list format:

Example

mylist = [1,2,3,4,5]
a,*b = mylist
print(f”a =”,a)
print(f”b =”,b)

Output

a = 1
b = [2, 3, 4, 5]

This method is also known as list unpacking, and it can be used with more than two variables!

9.  Lambda function

If you require a simple function, you can write it in one line with lambda. They are also known as anonymous functions, and they are widely used in data science and web development.

Suppose you want to construct a function that multiplies two numbers. Instead of writing a primary function, you can do it in a single line by using:

Example

mul = lambda a,b: a*b
mul(5,6)

Output

30

10. Compare two unordered lists

Assume you have two lists that both contain identical elements, but their order is different. As an example,

one = [33, 22, 11, 44, 55]
two = [22, 11, 44, 55, 33]

The elements in the two lists above are the same, but their order is different. Let’s examine how we can determine whether two lists are same.

We can use the collections.

  • If our object is hashable, we can use the counter method.
  • If the objects are orderable, we can use sorted().

Example

from collections import Counter

one = [33, 22, 11, 44, 55]
two = [22, 11, 44, 55, 33]

print("is two list are  equal", Counter(one) == Counter(two))

Output

'is two list are equal', True

Here is a book on Python programming that I would definitely recommend for all beginners.

Conclusion

These are some fantastic Python tricks that will make your coding life much easier. You may find many more shortcuts like these in the official manual or on any other website.

However, I have used the recommended material and it has aided me in my data science professional journey. If you find this post helpful then don’t forget to share this post with your friends and comment if you have any doubts. Have a great day ahead!

Share This Post, Help Others & Learn Together!

Leave a Reply

Your email address will not be published. Required fields are marked *