Amazing hacks of Python

In this tutorial, we will learn how awesome a Python language is for coding. We will discuss some of its amazing hacks, making Python the best among other languages.

Hacks of Python

Following are some amazingly cool hacks of Python that can make work easy for users and developers:

1. List Comprehensions: It is the best and efficient technique for getting rid of writing pointless lines of program.

List comprehension consists of the following parts:

  1. Output expression
  2. Input sequence
  3. A member of the input sequence represented by a variable
  4. The optional predicate parts.

Example:

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. Printing a List: Lists are not printed according to our requirements; they are always printed in unnecessary square brackets and single quotes. But in Python, we have a solution for printing lists efficiently by using the join method of string. The "join method" can turn the list into a string by classifying every item into a string and connecting them with the string on which the join method is used.

Example:

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, a user can implement the matrix as a nested list, which means a list inside a list. Every element of the list is treated as a row of the matrix.

Example:

Output:

Matrix 1: 
[5, 3]
[1, 2]
[9, 8]


Matrix 2: 
[5, 1, 9]
[3, 2, 8]

4. artition of List into "N" Groups: The users can use the iter() function as an iterator over the sequence.

Example:

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" which produced different groups containing two elements of the 'LIST_1[]' list. That is, the lists of length two will be generated using the elements from the first list.

5. Print more than One Item of List simultaneously

Example:

Output:

11 12
13 14
15 16
17 18

6. Take the String as Input and Convert it into List:

Example:

Output:

Input: 
 10 12 14 16 18 20 22
Output as Formatted list:  [10, 12, 14, 16, 18, 20, 22]

7. Convert List of Lists into Single List:

Example:

Output:

Iterated list of 'LIST_1':  [1, 2, 3, 4, 5, 6]

8. Print the Repeated Characters: Suppose our task is to print the patterns like "122333444455555666666". We can easily print this pattern in Python without using for loop.

Example:

Output:

122333444455555666666

Conclusion

In this tutorial, we have discussed 8 different amazing and cool hacks of Python, which makes it easy to work with for developers as well as beginners.