Refresh This website, www.javatpoint.com/amazing-python-hacks, is now unavailable. Always OnlineTM by Cloudflare displays a snapshot of this web page from the Internet Archive’s Wayback Machine. Click Refresh to see whether the live version is available.Python hacks that are incredibleIn this course, we will discover how fantastic the Python programming language is. We will go through some of the fantastic techniques that make Python the finest language among others.Python ModificationsThe following are some really interesting Python hacks that may make users and developers’ lives easier:1. Comprehensions from a List: It is the most effective and efficient method for eliminating the need to write unnecessary lines of code.List comprehension is made up of the following components:
Example:
- import functools as FT
- # First, filter odd numbers
- list_1 = filter(lambda K : K % 2 == 1, range(10, 30))
- print (“List: “, list(list_1))
- # Then we will filter the odd square which is divisible by 5
- list_1 = filter(lambda K : K % 5 == 0,
- [K ** 2 for K in range(1, 11) if K % 2 == 1])
- print (“ODD SQUARE WHICH IS DIVISIBLE BY 5: “, list(list_1))
- # Here, we will filter negative numbers
- list_1 = filter((lambda K : K < 0), range(-10, 10))
- print (“Filter negative numbers: “, list(list_1))
- # Now, implement by using the max() function
- print (“Maximum Number in the List: “)
- print (FT.reduce(lambda S, T: S if (S > T) else T, [14, 11, 65, 110, 105]))
# First, filter odd numbers
list_1 = filter(lambda K : K % 2 == 1, range(10, 30))
print (“List: “, list(list_1))
# Then we will filter the odd square which is divisible by 5
list_1 = filter(lambda K : K % 5 == 0,
[K ** 2 for K in range(1, 11) if K % 2 == 1])
print (“ODD SQUARE WHICH IS DIVISIBLE BY 5: “, list(list_1))
# Here, we will filter negative numbers
list_1 = filter((lambda K : K < 0), range(-10, 10))
print (“Filter negative numbers: “, list(list_1))
# Now, implement by using the max() function
print (“Maximum Number in the List: “)
print (FT.reduce(lambda S, T: S if (S > T) else T, [14, 11, 65, 110, 105]))
Output:
List: [11, 13, 15, 17, 19, 21, 23, 25, 27, 29] ODD SQUARE WHICH IS DIVISIBLE BY 5: [25] Filter negative numbers: [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1] Maximum Number in the List: 110
2. List Printing: Lists are not produced in accordance with our specifications; they are always written in superfluous square brackets and single quotes. Nevertheless, in Python, we have a way for efficiently printing lists by utilising the string join function. The “join method” may convert a list into a string by stringifying each item and attaching it to the string on which the join method is used.Example:
- # First declare the list:
- ABC = [‘LPG’, ‘WWF’, ‘XYZ’, ‘MPG’]
- # Then, we will print the list:
- print (“The Simple List: “, ABC)
- # HEre, we will Print the list by using join method
- print (‘The List by using join method: %s’ % ‘, ‘ .join(ABC))
- # we can directly apply Join Function on the List:
- print (‘Directly applying the join method: ‘, (“, “ .join(ABC)))
# Then, we will print the list:
print (“The Simple List: “, ABC)
# HEre, we will Print the list by using join method
print (‘The List by using join method: %s’ % ‘, ‘ .join(ABC))
# we can directly apply Join Function on the List:
print (‘Directly applying the join method: ‘, (“, ” .join(ABC)))
Output:
The Simple List: ['LPG', 'WWF', 'XYZ', 'MPG'] The List by using join method: LPG, WWF, XYZ, MPG Directly applying the join method: LPG, WWF, XYZ, MPG
3. Transpose a Matrix: In Python, the matrix may be implemented as a nested list, which is a list within a list. Every list item is considered as a row in the matrix.Example:
- M_1 = [[5, 3], [1, 2], [9, 8]]
- print (“Matrix 1: “)
- for row in M_1 :
- print (row)
- rez_1 = [[M_1[K][L] for K in range(len(M_1))] for L in range(len(M_1[0]))]
- print (“\n”)
- print (“Matrix 2: “)
- for row in rez_1:
- print (row)
print (row)
rez_1 = [[M_1[K][L] for K in range(len(M_1))] for L in range(len(M_1[0]))]
print (“\n”)
print (“Matrix 2: “)
for row in rez_1:
print (row)
Output:
Matrix 1: [5, 3] [1, 2] [9, 8] Matrix 2: [5, 1, 9] [3, 2, 8]
4. List division into “N” Groups: The iter() method may be used as an iterator across the series.Example:
- # First, we will Declare the list:
- LIST_1 = [‘E_1’, ‘E_2’, ‘E_3’, ‘E_4’, ‘E_5’, ‘E_6’]
- partition_1 = list(zip (*[iter(LIST_1)] * 2))
- print (“List after partitioning into different of groups of two elements: “, partition_1)
partition_1 = list(zip (*[iter(LIST_1)] * 2))
print (“List after partitioning into different of groups of two elements: “, partition_1)
Output:
List after partitioning into different of groups of two elements: [('E_1', 'E_2'), ('E_3', 'E_4'), ('E_5', 'E_6')]
Explanation: In the above code, we used “[iter(LIST 1)] * 2” to generate various groups having two entries from the ‘LIST 1[]’ list. That is, the components from the first list will be used to produce lists of length two.5. Print more than one list item at the same timeExample:
- list_1 = [11, 13, 15, 17]
- list_2 = [12, 14, 16, 18]
- # Here, we will use zip() function which will take 2 equal length list
- # and then merge them together into pairs
- for K, L in zip(list_1, list_2):
- print (K, L)
# Here, we will use zip() function which will take 2 equal length list
# and then merge them together into pairs
for K, L in zip(list_1, list_2):
print (K, L)
Output:
11 12 13 14 15 16 17 18
6. Using the String as input, convert it to a List:Example:
- # Reading a string from input as int format
- # after splitting it’s elements by white-spaces
- print (“Input: “)
- formatted_list_1 = list(map (int, input().split()))
- print (“Output as Formatted list: “, formatted_list_1)
Output:
Input: 10 12 14 16 18 20 22 Output as Formatted list: [10, 12, 14, 16, 18, 20, 22]
7. Turn a list of lists into a single list:
- # importing the itertools
- import itertools as IT
- # Declaring the list geek
- LIST_1 = [[1, 2], [3, 4], [5, 6]]
- # chain.from_iterable() function will return the
- # elements of nested list
- # and iterate it from first list
- # of iterable till the last
- # end of the list
- list_2 = list(IT.chain.from_iterable(LIST_1))
- print (“Iterated list of ‘LIST_1’: “, list_2)
# Declaring the list geek
LIST_1 = [[1, 2], [3, 4], [5, 6]]
# chain.from_iterable() function will return the
# elements of nested list
# and iterate it from first list
# of iterable till the last
# end of the list
list_2 = list(IT.chain.from_iterable(LIST_1))
print (“Iterated list of ‘LIST_1’: “, list_2)
Output:
Iterated list of 'LIST_1': [1, 2, 3, 4, 5, 6]
8. Print the Repetitive Characters: Assume our job is to print the patterns such as”
122333444455555666666
“This pattern can be readily printed in Python without the need of a for loop.Example:
- print (“1” + “2” * 2 + “3” * 3 + “4” * 4 + “5” * 5 + “6” * 6)
Output:
122333444455555666666
ConclusionIn this article, we reviewed 8 distinct great and fascinating Python hacks that make it easier to deal with for both developers and newbies.