Python Tips And Tricks Make Your Life Easier

Ali Aref
7 min readAug 5, 2021

--

Hi, and welcome to the python tips and trick which make your life easier!
In this post We gonna discuss about the most useful python tips and tricks. Most of these “tricks” are simple things I’ve used during my day-to-day work and I found some when browsing the Python_Standard_Library_docs and PyPi. So Let’s Start!

1. Multiple inputs from user

Some times you need to get multiple input from users so you use loops or any iterates, but the easier and better way

# bad practice
n1 = input("enter a number : ")
n2 = input("enter a number : ")
n2 = input("enter a number : ")
print(n1, n2, n3)
# good practice
n1, n2, n3 = input("enter a number : ").split()
print(n1, n2, n3)

2. In case you had many conditions

If you had to check many conditions in your code you can use all( ) or any( ) functions to achieve your goal. use all( ) when you had multiple and condition, use any( ) when you had many or conditions. That makes your code much cleaner and readable, so you won’t get into troubles while debugging.

size = "lg"
color = "blue"
price = 50
# bad practice
if size == "lg" and color == "blue" and price < 100:
print("Yes, I want to but the product.")
# good practice
conditions = [
size == "lg",
color == "blue",
price < 100,
]
if all(conditions):
print("Yes, I want to but the product.")
""" and the same for any() """# bad practice
if size == "lg" or color == "blue" or price < 100:
print("Yes, I want to but the product.")
# good practice
conditions = [
size == "lg",
color == "blue",
price < 100,
]
if any(conditions):
print("Yes, I want to but the product.")

3. Detecting odd or even numbers

It’s easy one, you get input from the user, convert it to integer, check the modules of number on 2, if the modules was zero, it’s even else it’s odd.

print('odd' if int(input('Enter a number: '))%2 else 'even')

4. Switch variables

To switch variables you don’t need to define a temp variable and go on. you can easily switch variables as

v1 = 100
v2 = 200
# bad practice
temp = v1
v1 = v2
v2 = temp
# good practice
v1, v2 = v2, v1

5. Reverse an string

The easiest way to reverse an string is to use [::-1]

print("John Deo"[::-1])

6. Checking if an string is palindrome

To check if an sting is palindrome (from right to left equal to left to right..) just use string.find(string[::-1])== 0

v1 = "madam" # is a palindrome string
v2 = "master" # is not a palindrome string
print(v1.find(v1[::-1]) == 0) # True
print(v1.find(v2[::-1]) == 0) # False

7. Inline if statement

Most of the time we have just one statement after a condition so using inline if statement helps us write cleaner code. if you are more interested about details of inline if statements and their usages, I would make an other post for that.

name = "ali"
age = 22
# bad practices
if name:
print(name)
if name and age > 18:
print("user is verified")
# a better approach
print(name if name else "")
""" here you have to define the else condition too"""
# good practice
name and print(name)
age > 18 and name and print("user is verified")

8. Remove duplicate items from a list

You don’t need to loop through the list to check duplicate items you can simply use set( ) to remove duplicated items

lst = [1, 2, 3, 4, 3, 4, 4, 5, 6, 3, 1, 6, 7, 9, 4, 0]
print(lst)
unique_lst = list(set(lst))
print(unique_lst)

to Sort this list you can use the sorted( ) function.

sorted_lst = sorted(lst)
reversed_sorted_lst = sorted(lst, reverse=True)

9. Most repeated item in a list

Finding out the most repeated item in a list is simple using max( ) function and passing the list.count as key.

lst = [1, 2, 3, 4, 3, 4, 4, 5, 6, 3, 1, 6, 7, 9, 4, 0]most_repeated_item = max(lst, key=lst.count)
print(most_repeated_item)

Note: for more efficient code pass set(lst) so that it count the again the repeated once again. as most_repeated_item = max(set(lst), key=lst.count) .

10. List comprehensions

One of my favourite things about programming in Python are its list comprehensions.

These expressions make it easy to write very clean code that reads almost like natural language.

You can read more about how to use them here.

numbers = [1,2,3,4,5,6,7]
evens = [x for x in numbers if x % 2 is 0]
odds = [y for y in numbers if y not in evens]
cities = ['London', 'Dublin', 'Oslo']def visit(city):
print("Welcome to "+city)
for city in cities:
visit(city)

11. Pass multi arguments using *args

You can use *args to get pass multiple arguments to a function here how is we handle it

def sum_of_squares(n1, n2)
return n1**2 + n2**2
print(sum_of_squares(2,3))
# output: 13
"""
what ever if you want to pass, multiple args to the function as n number of args. so let's make it dynamic.
"""
def sum_of_squares(*args):
return sum([item**2 for item in args])
# now you can pass as many parameters as you want
print(sum_of_squares(2, 3, 4))
print(sum_of_squares(2, 3, 4, 5, 6))

12. Item index during looping

I am sure once a time you wanted to get the index of the item your looping, here is a better way to do this task

lst = ["blue", "lightblue", "pink", "orange", "red"]
for idx, item in enumerate(lst):
print(idx, item)

it’s always better to use enumerate while looping.

13. save memory using generators

Using generator we can save lots of memory than using list comprehension here is how to save, and see how much memory we save.

# for a bigger list as
lst = [i for i in range(10000)] # using comprehension
lst2 = (i for i in range(10000)) # using generator
# let's print sum of both lists (both are the same)
print(sum(lst))
print(sum(lst2))
# now let's compare the memory sizes
import sys
print(sys.getsizeof(lst), "bytes") # 87624 bytes
print(sys.getsizeof(lst2), "bytes") # 120 bytes

so you can see we saved almost `87504` bytes.

14. Concatenate list elements to in a single string

Using Join( ) function you can concatenate all list elements to a single string as follow and also you can join them with any character not “, ”

names = ["john", "sara", "jim", "rock"]
print(", ".join(names))

15. Merge two or more dictionaries

We can merge many dictionaries using {**dict_name, **dict_name2, … }

d1 = {"v1": 22, "v2": 33}
d2 = {"v2": 44, "v3": 55}
d3 = {**d1, **d2}
print(d3)

16. Check an object attributes

Ever wondered how you can look inside a Python object and see what attributes it has? Of course you have. To check an object attributes using dir( ) funtion

dir("hello world")

This can be a really useful feature when running Python interactively, and for dynamically exploring objects and modules you are working with.

Read more here.

17. Emojies in python

If you are emoji lover, then emoji module is for you. install the emoji module as pip install emoji . you can find out all emojies in here.

import emoji
print(emoji.emojize(":sad_but_relieved_face:"))

18. Mapping a list

Python supports functional programming through a number of inbuilt features. One of the most useful is the map() function — especially in combination with lambda functions.

x = [1, 2, 3]
y = list(map(lambda x: x + 1, x)) # adding one to each list item
y = list(map(lambda x: x ** 2, x)) # square each list item

19. Pretty print

Print() function, some times prints the output really ugly, so using the pprint the output would be more prettier.

from pprint import pprintdata = {
"name": "john deo",
"age": "22",
"address": {"contry": "canada", "state": "an state of canada :)", "address": "street st.34 north 12"},
"attr": {"verified": True, "emialaddress": True},
}
print("print : ", data)
pprint("pprint : ", data)

20. Easiest way to generate Universally Unique IDs

A quick and easy way to generate Universally Unique IDs (or ‘UUIDs’) is through the Python Standard Library’s uuid module.

import uuiduser_id = uuid.uuid4()
print(user_id)

This creates a randomized 128-bit number that will almost certainly be unique.

In fact, there are over ²¹²² possible UUIDs that can be generated. That’s over five undecillion (or 5,000,000,000,000,000,000,000,000,000,000,000,000).

The probability of finding duplicates in a given set is extremely low. Even with a trillion UUIDs, the probability of a duplicate existing is much, much less than one-in-a-billion.

21. Python wikipedia module

Wikipedia has a great API that allows users programmatic access to an unrivalled body of completely free knowledge and information.

The wikipedia module makes accessing this API almost embarrassingly convenient.

import wikipedia

result = wikipedia.page('freeCodeCamp')
print(result.summary)

for link in result.links:
print(link)

Like the real site, the module provides support for multiple languages, page disambiguation, random page retrieval, and even has a donate() method.

22. Form a dictionary out of two lists

Ever needed to form a dictionary out of two lists? If yes, so this how to do it using zip function.

keys = ['a', 'b', 'c']
vals = [1, 2, 3]
zipped = dict(zip(keys, vals))

23. Sort a dictionary by it’s values

Sorting dictionary by it’s values are easily possible using sorted( ) function

d = {
"v1": 80,
"v2": 20,
"v3": 40,
"v4": 20,
"v5": 10,
}
sorted_d = dict(sorted(d.items(), key=lambda item: item[1]))
print(sorted_d)

you can use itemgetter( ) instate of using lambda functions as

from operator import itemgetter
sorted_d = dict(sorted(d.items(), key=itemgetter(1)))

also you can sort it descending by passing reverse=True

sorted_d = dict(sorted(d.items(), key=itemgetter(1), reverse=True))

Hopefully you’ve found something useful for your next project.

Python’s a very diverse and well-developed language, so there’s bound to be many features I haven’t got round to including.

Please share any of your own favorite Python tricks by leaving a response below!

--

--

Responses (3)