In this article, Your going to learn some useful tricks and tips which you can utilize while coding with python. It will help you to write python code efficiently and productively.
I will give a brief explanation for every example below. so that you can understand it easily.
Table of Contents:
- Swapping of two Numbers
- Using Multiple Comparison Operators
- Python Ternary Operator
- Storing List Items Into Variables
- Inspecting An Object In Python
- Simplify The if Statements
- Reversing A String
- Check The Size Of An Object
- Using Enumerate
- Print Key, Value Of Dict At A Time
- Using List Comprehensions To Create Sets, Dictionaries
- Removing Duplicates From List
Let's explore some cool Python tricks and tips.
Tricks and Tips
#1. Swapping of two Numbers
Python provides an easy way to swap two numbers. You can swap two numbers by changing the positions of variable names. See the example below.
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
a, b = b, a #it interchanges the a and b values
print("a is {} and b is {}".format(a, b))
In the above code, first we have taken two numbers input from the user. Next, we swap the two numbers using in place python swapping feature. That is a, b = b, a
.
#2. Using Multiple Comparison Operators
You can check whether a number is in the given range or not using this feature. It's convenient to write. Let's see an example.
n = 10
#the following statement is same as 1 < n and n <= 10
output = 1 < n <= 10
print(output) #it prints True
#the following statement is same as 1 < n and n < 10
output = 1 < n < 10
print(output) #it prints False
You can use this kind of comparisons in your code to reduce the number of lines and to increase the productivity of your code.
#3. Python Ternary Operator
Python has a ternary operator same as C language or Java. But, python's ternary operator is more like an English sentence.
Following is the syntax:
[statement when true] if [condition] else [statement when false]
Statement when true is executed, when the condition is true otherwise the statement when false is executed. See the following example.
print("It's True") if True else print("False") #it prints True
print("It's True") if False else print("False") #it prints False
You can write any statement in place of the print statement like assigning, appending, removing, etc, based on your requirements. Let's see an example where we assign values.
y = 1
y = 7 if y == 1 else 5
print(y) #it prints 7
x = 6
x += 1 if x == 6 else 2
print(x) #it prints 7
The second statement will assign 7
to the variable y
. In case, if the condition is false, it will assign 5
to the variable y
.
What about the 5th statement, what it will do is that if the condition is true then it adds 1
to x
else it adds 2
to the x
. Try to print the program two times then you will see the difference.
If you execute it two times, then the value of x
becomes 9. Try it, you will see.
We can also use ternary operator in list comprehensions. See the following example,
evens = [i for i in range(10) if i % 2 == 0]
print(evens) #it prints [0, 2, 4, 6, 8]
The statement checks all the time whether i
is divisible by 2
or not. If i
is divisible by 2
, then it's added to the list.
#4. Storing List Items Into Variables
You can unpack a python list to assign the values to variables directly. The number of variables should be equal to the number of elements in the list else you will get an error.
See the following example.
evens = [2, 4, 6]
x, y, z = evens
print(x, y, z) #it prints 2 4 6
#5. Inspecting An Object In Python
We can see all the methods and magic variables of any object using the dir
method in python. Let's see an example for it.
print(dir(list)) #it prints all the methods and magic variables of list
You can also see the description of any method(for the ones enlisted using dir
method also) using help()
function.
print(help(list.reverse)) #it prints the short description of the reverse method of list
#6. Simplifying the if
Statements
Use clear conditions while using the if
conditions. See the case below.
x = 5
if x in [1, 2, 3, 4, 5]:
print(x)
if x == 1 or x == 2 or x == 3 or x == 4 or x == 5:
print(x)
You can see that the first style is more convenient to write than the second one. So avoid using long statements as conditions.
#7. Reversing A String
You can reverse a string in only one step. See the below example.
string = input("Enter a string: ")
print(string[::-1]) #it prints the reverse of the given string
You must be thinking how's it happening. To know how it works first, read the slicing concept in Python then you will understand it. You can also apply the same method for any list.
#8. Check The Size Of An Object
You check the size of an object in python using sys
module's method getsizeof
()
. Let's see an example.
import sys
x = 7
print(sys.getsizeof(x)) #it prints 28
#9. Using Enumerate
If you want to print the list of elements along with their indices, use the enumerate
function.
evens = [2, 4, 6]
for i, j in enumerate(evens):
print("{}: {}".format(i, j)
#it prints like this
# 0: 2
# 1: 4
# 2: 6
You can use enumerate
function for tuples
also.
#10. Print Key-Value of Dict, one at a Time
Use the items()
method of the dictionary to print key and value at the same time. See the following example.
d = {'a':1, 'b':2, 'c':3}
for key, value in d.items():
print("{}: {}".format(key, value)
#it prints like this
# a: 1
# b: 2
# c: 3
#11. Using List Comprehensions to Create Sets, Dictionaries
We can use list comprehensions to create dictionaries and sets. If you assign key:value pair then it is a dictionary, otherwise, it's a set. Let's see an example.
simple_dict = {i : i ** 2 for i in range(10)}
simple_set = {i for i in range(10)}
print(simple_dict) #it prints {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
print(simple_set) #it prints {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
#12. Removing Duplicates From List
You can remove duplicates from the list using the set
method. Set only contains the different values. So, when you convert a list to set, then it automatically removes the duplicate values from the list. See the following example.
evens = [0, 2, 4, 6, 8, 2, 4]
print(list(set(evens))) #it prints [0, 2, 4, 6, 8]
You can also use the same method on tuples.
Conclusion:
Now, you will able to write the Python code more productively. I hope you have learned something new here. If you have any doubts regarding the article or anything related to Python, please comment below. We will definitely help you.
Stay tuned for more amazing tutorials like this.
You may also like: