30 Magical Python Tricks to Write Better Code

栏目: IT技术 · 发布时间: 4年前

内容简介:Python is quite a popular language among others for its simplicity and readability of the code. It is one of the simplest languages to choose as your first language. If you are a beginner with the basic concepts of python then this is the best time to lear

Python is quite a popular language among others for its simplicity and readability of the code. It is one of the simplest languages to choose as your first language. If you are a beginner with the basic concepts of python then this is the best time to learn to write better codes.

There are a lot of tricks in python that can improve your program better than before. This article will help you to know various tricks and tips available in python. Practice them continuously until it becomes a part of your programming habit.

Trick 01 – Multiple Assignment for Variables

Python allows us to assign values for more than one variable in a single line. The variables can be separated using commas. The one-liners for multiple assignments has lots of benefits. It can be used for assigning multiple values for multiple variables or multiple values for a single variable name. Let us take a problem statement in which we have to assign the values 50 and 60 to the variables a and b. The usual code will be like the following.

a = 50 
b = 60
print(a,b)
print(type(a))
print(type(b))

Output

50 60
<class 'int'>
<class 'int'>

Condition I – Values equal to Variables

When the variables and values of multiple assignments are equal, each value will be stored in all the variables.

a , b = 50 , 60
print(a,b)
print(type(a))
print(type(b))

Output

50 60
<class 'int'>
<class 'int'>

Both the programs gives the same results. This is the benefit of using one line value assignments.

Condition II – Values greater than Variables

Let us try to increase the number of values in the previous program. The multiple values can be assigned to a single variable. While assigning more than one value to a variable we must use an asterisk before the variable name.

a , *b = 50 , 60 , 70
print(a)
print(b)
print(type(a))
print(type(b))

Output

50
[60, 70]
<class 'int'>
<class 'list'>

The first value will be assigned to the first variable. The second variable will take a collection of values from the given values. This will create a list type object.

Condition III – One Value to Multiple Variables

We can assign a value to more than one variable. Each variable will be separated using an equal to symbol.

a = b = c = 50
print(a,b,c)
print(type(a))
print(type(b))
print(type(c))

Output

50 50 50
<class 'int'>
<class 'int'>
<class 'int'>

Trick 02 – Swapping Two Variables

Swapping is the process of exchanging the values of two variables with each other. This can be useful in many operations in computer science. Here, I have written two major methods used by the programmer to swap the values as well as the optimal solution.

Method I – Using a temporary variable

This method uses a temporary variable to store some data. The following code is written with temporary variable name.

a , b = 50 , 60
print(a,b)
temp = a+b  #a=50 b=60 temp=110
b = a       #a=50 b=50 temp=110
a = temp-b  #a=60 b=50 temp=110
print("After swapping:",a,b)

Output

50 60
After swapping: 60 50

Method II – Without using a temporary variable

The following code swaps the variable without using a temporary variable.

a , b = 50 , 60
print(a,b)
a = a+b  #a=110 b=60
b = a-b  #a=110 b=50
a = a-b  #a=60  b=50
print("After swapping:",a,b)

Output

50 60
After swapping: 60 50

Method III – Optimal Solution in Python

This is a different approach to swap variables using python. In the previous section, we have learned about multiple assignments. We can use the concept of swapping.

a , b = 50 , 60
print(a,b)a , b = b , a
print("After swapping",a,b)

Output

50 60
After swapping 60 50

Trick 03 – Reversing a String

There is an another cool trick for reversing a string in python. The concept used for reversing a string is called string slicing. Any string can be reversed using the symbol [::-1] after the variable name.

my_string = "MY STRING"
rev_string = my_string[::-1]
print(rev_string)

Output

GNIRTS YM

Trick 04 – Splitting Words in a Line

No special algorithm is required for splitting the words in a line. We can use the keyword split() for this purpose. Here I have written two methods for splitting the words.

Method I – Using iterations

my_string = "This is a string in Python"
start = 0
end = 0
my_list = []for x in my_string:
    end=end+1
    if(x==' '):
        my_list.append(my_string[start:end])
        start=end+1
my_list.append(my_string[start:end+1])
print(my_list)

Output

['This ', 'is ', 'a ', 'string ', 'in ', 'Python']

Method II – Using split function

my_string = "This is a string in Python"
my_list = my_string.split(' ')
print(my_list)

Output

['This ', 'is ', 'a ', 'string ', 'in ', 'Python']

Trick 05 – List of words into a line

This is the opposite process of the previous one. In this part we are going to convert a list of words into a single line using join function. The syntax for using join function is given below.

Syntax:“ ”.join(string)

my_list = ['This' , 'is' , 'a' , 'string' , 'in' , 'Python']
my_string = " ".join(my_list)

Output

This is a string in Python

Trick 06 – Printing a string multiple times

We can use the multiplication operator to print a string for multiple times. This is a very effective way to repeat a string.

n = int(input("How many times you need to repeat:"))
my_string = "Python\n"
print(my_string*n)

Output

How many times you need to repeat:3
Python
Python
Python

Trick 07 – Joining Two strings using addition operator

Joining various strings can be done without using the join function. We can just use the addition operator (+) to do this.

a = "I Love "
b = "Python"
print(a+b)

Output

I Love Python

Trick 08 – More than one Conditional Operators

Two combine two or more conditional operators in a program we can use the logical operators. But the same result can be obtained by chaining the operators. For example, if we need to do print something when a variable has the value greater than 10 and less than 20, the code will be something like the following.

a = 15
if (a>10 and a<20):
    print("Hi")

Instead of this we can combine the conditional operator into single expression.

a = 15
if (10 < a < 20):
    print("Hi")

Output

Hi

Learn more about operators in the following article.

Trick 09 – Find most frequent element in a list

The element which occurs most of the time in a list then it will be the most frequent element in the list. The following snippet will help you to get the most frequent element from a list.

my_list = [1,2,3,1,1,4,2,1]
most_frequent = max(set(my_list),key=my_list.count)
print(most_frequent)

Output

Trick 10 – Find Occurrence of all elements in list

The previous code will give the most frequent value. If we need to know the occurrence of all the unique element in a list, then we can go for the collection module. The collections is a wonderful module in python which gives great features. The Counter method gives a dictionary with the element and occurrence pair.

from collections import Counter
my_list = [1,2,3,1,4,1,5,5]
print(Counter(my_list))

Output

Counter({1: 3, 5: 2, 2: 1, 3: 1, 4: 1})

Trick 11 – Checking for Anagram of Two strings

Two strings are anagrams if one string is made up of the characters in the other string. We can use the same Counter method from the collections module.

from collections import Counter
my_string_1 = "RACECAR"
my_string_2 = "CARRACE"
if(Counter(my_string_1) == Counter(my_string_2)):
print("Anagram")
else:
print("Not Anagram")

Output

Anagram

Trick 12 – Create Number Sequence with range

The function range() is useful for creating a sequence of numbers. It can be useful in many code snippets. The syntax for a range function is written here.

Syntax:range(start, end, step)

Let us try to create a list of even numbers.

my_list = list(range(2,20,2))
print(my_list)

Output

[2, 4, 6, 8, 10, 12, 14, 16, 18]

Trick 13 – Repeating the element multiple times

Similar to the string multiplication we can create a list filled with an element multiple times using multiplication operator.

my_list = [3]
my_list = my_list*5
print(my_list)

Output

[3, 3, 3, 3, 3]

Trick 14 – Using Conditions in Ternary Operator

In most of the time, we use nested conditional structures in Python. Instead of using nested structure, a single line can be replaced with the help of ternary operator. The syntax is given below.

Syntax:Statement1 if True else Statement2

age = 25

print(“Eligible”) if age>20 else print(“Not Eligible”)

Output

Eligible

Trick 15 – List Comprehension with Python

List comprehension is a very compact way to create a list from another list. Look at the following codes. The first one is written using simple iteration and the second one is created using list comprehension.

square_list = []
for x in range(1,10):
    temp = x**2
    square_list.append(temp)
print(square_list)

Output

[1, 4, 9, 16, 25, 36, 49, 64, 81]

Using List Comprehension

square_list = [x**2 for x in range(1,10)]
print(square_list)

Output

[1, 4, 9, 16, 25, 36, 49, 64, 81]

Trick 16 – Convert Mutable into Immutable

The function frozenset() is used to convert mutable iterable into immutable object. Using this we can freeze an object from changing its value.

my_list = [1,2,3,4,5]
my_list = frozenset(my_list)
my_list[3]=7
print(my_list)

Output

Traceback (most recent call last):
  File "<string>", line 3, in <module>
TypeError: 'frozenset' object does not support item assignment

As we applied the frozenset() function on the list, the item assignment is restricted.

Trick 17 – Rounding off with Floor and Ceil

Floor and Ceil are mathematical functions can be used on floating numbers. The floor function returns an integer smaller than the floating value whereas the ceil function returns the integer greater than the floating value. To use this functions we have to import math module.

import math
my_number = 18.7
print(math.floor(my_number))
print(math.ceil(my_number))

Output

Trick 18 – Returning Boolean Values

Some times we have to return a boolean value by checking conditions of certain parameters. Instead of writing if else statements we can directly return the condition. The following programs will produce the same output.

Method I – Using If Else Condition

def function(n):
    if(n>10):
        return True
    else:
        return False
n = int(input())
if(function(n)):
    print("Eligible")
else:
    print("Not Eligible")

Method II – Without If Else Condition

def function(n):
    return n>10n = int(input())
print("Eligible") if function(n) else print("Not Eligible")

Output

11
Eligible

Trick 19 – Create functions in one line

Lambda is an anonymous function in python that creates function in one line. The syntax for using a lambda function is given here.

Syntax:lambda arguments: expression

x = lambda a,b,c : a+b+c
print(x(10,20,30))

Output

Trick 20 – Apply function for all elements in list

Map is a higher order function that applies a particular function for all the elements in list.

Syntax: map(function, iterable)

my_list = ["felix", "antony"]
new_list = map(str.capitalize,my_list)
print(list(new_list))

Output

['Felix', 'Antony']

Trick 21 – Using Lambda with Map function

The function can be replaced by a lambda function in python. The following program is created for creating square of list of numbers.

my_list = [1, 2, 3, 4, 5]
new_list = map(lambda x: x*x, my_list)
print(list(new_list))

Output

[1, 4, 9, 16, 25]

Learn more about higher order functions here.

Trick 22 – Return multiple values from a function

A python function can return more than one value without any extra need. We can just return the values by separating them by commas.

def function(n):
    return 1,2,3,4
a,b,c,d = function(5)
print(a,b,c,d)

Output

Trick 23 – Filtering the values using filter function

Filter function is used for filtering some values from a iterable object. The syntax for filter function is given below.

Syntax:filter(function, iterable)

def eligibility(age):
    return age>=24
list_of_age = [10, 24, 27, 33, 30, 18, 17, 21, 26, 25]
age = filter(eligibility, list_of_age)print(list(age))

Output

[24, 27, 33, 30, 26, 25]

Trick 24 – Merging Two Dictionaries in Python

In python, we can merge two dictionaries without any specific method. Below code is an example for merging two dictionaries.

dict_1 = {'One':1, 'Two':2}
dict_2 = {'Two':2, 'Three':3}
dictionary = {**dict_1, **dict_2}
print(dictionary)

Output

{'One': 1, 'Two': 2, 'Three': 3}

Trick 25 – Getting size of an object

The memory size varies based on the type of object. We can get the memory of an object using getsizeof() function from the sys module.

import sys
a = 5
print(sys.getsizeof(a))

Output

Trick 26 – Combining two lists into dictionary

The zip unction has many advantages in python. Using zip function we can create a dictionary from two lists.

list_1 = ["One","Two","Three"]
list_2 = [1,2,3]
dictionary = dict(zip(list_1, list_2))
print(dictionary)

Output

{'Two': 2, 'One': 1, 'Three': 3}

Trick 27 – Calculating execution time for a program

Time is another useful module in python can be used to calculate the execution time.

import time
start = time.clock()
for x in range(1000):
    pass
end = time.clock()
total = end - start
print(total)

Output

0.00011900000000000105

Trick 28 – Removing Duplicate elements in list

An element that occurs more than one time is called duplicate element. We can remove the duplicate elements simply using typecasting.

my_list = [1,4,1,8,2,8,4,5]
my_list = list(set(my_list))
print(my_list)

Output

[8, 1, 2, 4, 5]

Trick 29 – Printing monthly calendar in python

Calendar module has many function related to the date based operations. We can print monthly calendar using the following code.

import calendar
print(calendar.month("2020","06"))

Output

     June 2020
Mo Tu We Th Fr Sa Su
 1  2  3  4  5  6  7
 8  9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30

Trick 30 – Iterating with zip function

The zip functions enables the process of iterating more than one iterable using loops. In the below code two lists are getting iterated simultaneously.

list_1 = ['a','b','c']
list_2 = [1,2,3]
for x,y in zip(list_1, list_2):
    print(x,y)

Output

a 1
b 2
c 3

Closing Thoughts

I hope you enjoyed this article. As an end note, you have to understand that learning the tricks is not a must. But if you do so, you can stand unique among other programmers. Continuous practice is must to become fluent in coding. Thank you for reading this article. You can follow me on medium .

Happy Coding!


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

认知与设计

认知与设计

Jeff Johnson / 张一宁、王军锋 / 人民邮电出版社 / 2014-8-1 / CNY 69.00

本书语言清晰明了,将设计准则与其核心的认知学和感知科学高度统一起来,使得设计准则更容易地在具体环境中得到应用。涵盖了交互计算机系统设计的方方面面,为交互系统设计提供了支持工程方法。不仅如此,这也是一本人类行为原理的入门书。一起来看看 《认知与设计》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具