8 Advance Python tricks
In this article i will try to deliver you some cool tricks which you can use in your python code to make it more performant and simple.
Here are the 8 tricks, your code will definitely look more technical.
1. Sorting Object by Multiple keys
Lets consider that we have to sorting the list of given dictionaries
people = [
{ 'name':
'ram', "age":
24 },
{ 'name':
'rohit', "age":
34 },
{ 'name':
'sam', "age":
26 },
{ 'name':
'ajit', "age":
54 },
{ 'name':
'amit', "age":
32 },
{ 'name':
'dom', "age":
34 },
{ 'name':
'brian', "age":
92 },
]
but the problem is we want to sort it by both name and age, not only by the name or age. In SQL we can do that by the code :
SELECT * FROM people ORDER by name, age
In python there is a very simple solution present i.e sort function. Lets try this and check the output.
import operator
people.sort(key=operator.itemgetter('age'))
people.sort(key=operator.itemgetter('name'))
output :
[{'name': 'ajit', 'age': 54},
{'name': 'amit', 'age': 32},
{'name': 'brian', 'age': 92},
{'name': 'dom', 'age': 34},
{'name': 'ram', 'age': 24},
{'name': 'rohit', 'age': 34},
{'name': 'sam', 'age': 26}]
In this result you can see that names are sorted first then the age, if names are found sane then they will group together.
2. List Comprehension
List comprehension removes all the complexities created due to for loops. Lets see the basic syntax fofr the list comprehension.
[ expression for item in list if conditional ]
Now have a look in a very basic example
squares = []
for i in range(1,10):
squares.append(i**2)
print(squares)
output :
[1, 4, 9, 16, 25, 36, 49, 64, 81]
Now lets see an simple example
squares2 = [i**2 for i in range (1,11)]
print(squares2)
output :
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Negative no. of list by simple form
negative = []
for i in range (1,11):
negative.append(-i)
print(negative)
output :
[-1, -2, -3, -4, -5, -6, -7, -8, -9, -10]
An example with 'if' to filter the list
filtered = [i for i in range(20) if i%2==0]
print(filtered)
output :
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
3. Checking memory usage of an object
import sys
mylist = range(0, 2000)
print(sys.getsizeof(mylist))
you should think that why this huge list only have 48 bytes
It’s because the range function returns a class that only behaves like a list. A range is a lot more memory efficient than using an actual list of numbers.
You can see for yourself by using a list comprehension to create an actual list of numbers from the same range:
import sys
myreallist = [x for x in range(0, 25000)]
print(sys.getsizeof(myreallist))
4. Data Classes
since version 3.7 of python offers the data classes.
There are several advantages over regular classes or other alternatives like returning multiple values or dictionaries:
- a data class requires a minimal amount of code
- you can compare data classes because
__eq__
is implemented for you - you can easily print a data class for debugging because
__repr__
is implemented as well - data classes require type hints, reduced the chances of bugs
from dataclasses import dataclass
@dataclass
class Card:
rank: str
suit: str
card = Card("Q", "hearts")
print(card == card)
# True
print(card.rank)
# 'Q'
print(card)
Card(rank='Q', suit='hearts')
5. The attrs Package
If you want more features or you are using an older version of python then you can use the attrs packages.
@attrs
class Person(object):
name = attrib(default='John')
surname = attrib(default='Doe')
age = attrib(init=False)
p = Person()
print(p)
p = Person('Bill', 'Gates')
p.age = 60
print(p)
output :
Person(name='John', surname='Doe', age=NOTHING)
Person(name='Bill', surname='Gates', age=60)
6. Merging two Dictionaries
dict1 = { 'a': 1, 'b': 2 }
dict2 = { 'b': 3, 'c': 4 }
merged = { **dict1, **dict2 }
print (merged)
Note : here ** is used to unpack the dictionary
7. Find the Most Frequently Occurring Value
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
print(max(set(test), key = test.count))
This code is working because max() returns the highest value in the list
test.count
is a built-in function of list. It takes an argument and will count the number of occurrences for that argument.
set() returns all the unique values from test, so {1, 2, 3, 4}
8. Return Multiple Values
Functions in Python can return more than one variable without the need for a dictionary, a list, or a class. It works like this:
def get_user(id):
# fetch user from database
# ....
return name, birthdate
name, birthdate = get_user(4)
Recommended Post :
#python certification
#microsoft python certification
#python certification cost
#python online course certification
6 Comments
Learned very much new !!! Thnks buddy.
ReplyDelete👍👍
ReplyDeleteInformative ;)
ReplyDeleteThis text is copyrighted by me. If you don't take this article down within 3 days, I'll send the official request through my lawyer.
ReplyDeletegreat information
ReplyDeleteBest digital marketing
I liked this article very much. The content is very good. Keep posting.
ReplyDeletePython Online Training
If you have any doubt, Please let me know.