SoFunction
Updated on 2024-11-16

The 20 most useful python hacks

1. Arrangement with itertools

In this program, we import the built-in module called itertools. Using itertools, you can find all permutations of a given string. There are many ways to do this in itertools, you can try combinations and other methods

import itertools
name= 'Python'
for i in (name):
print(i)

2. Single-line conditional expressions

This conditional expression has been added to Python version 2.5. This can be used in conjunction with theA if condition else Bsyntax together. First, the condition is evaluated and returned based on the boolean value of the condition. If true, A is returned, otherwise, if false, B is returned.

x=10
 
y=100
 
res = x if x>y else y
 
print(f"The greater number is {res}")

3. Reversing strings

In this program, we use extended slices to invert strings; extended slices use the[begin:end:step]Syntax. So when we skip the start, end and step, we pass (-1) as the value. This will invert the given string.

string = "medium"
 
reverse_string = string[::-1]
 
print(f"The reversed string is {reverse_string}")

4. Handling exceptions with Assert

Exception handling is a very important concept in programming. An error statement is printed using the assert keyword and the given condition. If the given condition is not true then it prints an error message and terminates the program.

x = int(input("enter a number to divide "))
 
assert x<=-1 and x>0, 'Number should be greater than 0'
 
ans = 100/x
 
print(f'The output is {ans}')

5. Use of splitting for multiple inputs

split() is one of the string methods that splits a string into a list. The default separator used in this method is a space. In this program, instead of creating three duplicate lines for the input operation, it replaces them with a single line.

a,b,c = input("Enter the value for a, b, c :").split()
 
print(a)
 
print(b)
 
print(c)

6. Transpose the matrix with zip()

The Zip function has any number of iterable objects from different columns and aggregates the corresponding tuples. The asterisk (*) operator is used to unzip the list. Later the list is changed to the transpose matrix of the given list.

matrix=[[1,2],[3,4],[5,6]]
 
trans=zip( *matrix)
 
print(list(trans))

7. Resource Context Manager

Resource management is one of the important tasks in the programming process. Accessing and releasing files, locks and other resources is a hectic task. Failure to close resources properly can lead to several problems such as memory leaks. To solve this problem, instead of using the open and close methods every time, use the context manager shown in the code snippet.

with open("", mode="w") as file:
 
('Hola!')

8. Underlining as a separator

When using large numbers in a program, using underscores instead of commas as separators improves readability.The Python syntax does not recognize underscores. It uses underscores to represent numbers in the preferred format and to be readable.

x = 10_000_000_000
 
print(f" It is Ten Billion: {x}")

9. Attempts f String format

The F string format was introduced in Python version 3.6. It is the simplest and easiest way to format strings. Using the f-string format instead of the traditional format makes the code easy to understand.

Name = input("Enter your name ")
 
print(f'Hello{Name}! This is a Python Example')

10. Use this trick to exchange integers

Note that swapping integers is done without the use of temporary variables.Python computes expressions from left to right, but in assignment operations, the right side is computed first. This creates tuples for the right-hand side variables (b and a) whose values are assigned from the left-hand side variables. This process helps in swapping variables.

a,b = input("Enter the value for a, b :").split()
 
a,b = b,a
 
print(a,b)

11. Using lambda instead of functions

Lambda is one of the most powerful functions, also known as anonymous functions. It doesn't need a name or a function definition or a return statement. While normal functions use the def keyword, lambda functions use the lambda keyword. It works like a function, except that it only applies to one expression.

x = lambda a, b : a + b
 
print(x(1, 2))

12. Multiple prints without loops

In this program, we try to print statements multiple times using a single line instead of a loop. The asterisk (*) enables you to print the statement a specified number of times.

print("This is a Python example to print this 100 timesn" *100)

13. Unpacking strings into variables

A sequence or a string can be unpacked into different variables. In this program, the python string letters will be unpacked into separate variables. The output of the program will be p, y, t.

name='Python'
 
a,b,c,d,e,f =name
 
print(a)
 
print(b)
 
print(c)

14. List comprehension using Map

In this program, we are trying to add elements to a list. To do this, we use the lambda function in conjunction with map and list comprehension. The output of this program will be [12, 15, 18].

num1=[1,2,3]
 
num2= [4,5,6]
 
num3=[7,8,9]
 
result= map(lambda x,y,z:x+y+z,num1,num2,num3)
 
print(list(result))

15. Remove duplicates from the list

In this program, we try to remove duplicate items from a list. One thing to remember is that sets do not allow duplicates. We pass the list to set() and again change it to a list, removing all duplicate elements from the list.

old_list = [1,2,2,3,3,4,5,5,6]
 
new_list = list(set(old_list))
 
print(new_list)

16. Conditions in print statements

This program is interesting and contains quite a few operations. First, it will execute the input method and then change the input value to an integer. It will then check the condition and return a boolean value. If it returns, a non-zero number odd will be output, or, if it returns zero, then an even number will be output.

print("odd" if int(input("enter the value"))%2 else "even")

17. Conditional lists All and Any

In this program, we check a list of conditions one at a time. There are two functions: all() and any(). As the name suggests, when we use all(), all conditions must be true. And when using any(), the code block is executed even if one of the conditions is true.

Marks = 350
 
Percentage = 60
 
Passed = 5
 
Conditions = [Marks>200, Percentage>50,Passed>4]
 
if(all(Conditions)):
 
print("Hired for a company A")
 
elif(any(Conditions)):
 
print("Hired for a company B")
 
else:
 
print("Rejected")

18. Merging of two dictionaries

This one is now obsolete.

In this program, we try to merge two dictionaries. Note that in this program, the merge can be completed using "|" Operator

Household = {'Groceries':'100','Electricity':'150'}
 
Travel = {'Food':'50','Accomodation':'122','Transport':'70'}
 
Expense = Household | Travel
 
print(Expense)

19. Checking execution time

Check the execution time of a program by importing the timeit package. In this program, form a list of 1 to 1000 execution times.

import timeit
 
execution_time = ('list(range(1,1000))')
 
print(execution_time)

20. Check the function library

In this program, we try to check the library of the function. all the properties and modules of itertools are printed with this program.

import itertools
 
print(dir(itertools))

To this article on the most practical 20 python tips on the article is introduced to this, more relevant and practical python tips content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!