This content originally appeared on DEV Community and was authored by Vadim Kolobanov
Hello everyone! Let's see together what elegant mechanics professional Python developers use in their code
I very often see such examples in some public Git repositories of experienced programmers.
Let's get started
Sorting data by multiple keys
peoples = [
{ 'name': 'John', "age": 64 },
{ 'name': 'Janet', "age": 34 },
{ 'name': 'Ed', "age": 24 },
{ 'name': 'Sara', "age": 64 },
{ 'name': 'John', "age": 32 },
{ 'name': 'Jane', "age": 34 },
{ 'name': 'John', "age": 52 },
]
peoples.sort(key=lambda item: (item['name'], item['age']))
print(people)
#Output
[
{'name': 'Ed', 'age': 24},
{'name': 'Jane', 'age': 34},
{'name': 'Janet','age': 34},
{'name': 'John', 'age': 32},
{'name': 'John', 'age': 52},
{'name': 'John', 'age': 64},
{'name': 'Sara', 'age': 64}
]
at the output, we get alphabetical sorting, and if the values match, the sorting takes place by the second key. This will not have an effect if there are no duplicate values in your data.
List comprehensions (List Generator)
I have already shown an understanding of the list in my previous articles, here I will just show you a few possible uses
Basic syntax
[ expression for item in list if conditions ]
A very simple example to fill in a list is a sequence of numbers:
mylist = [i for i in range(10)]
print(mylist)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
And since you can use an expression, you can also do some math.:
squares = [x**2 for x in range(10)]
print(squares)
#output
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
You can call a function as an expression
def some_function(a):
return (a + 5) / 2
result = [some_function(i) for i in range(10)]
print(result)
#output
[2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0]
And finally, you can use "if" to filter the list. In this case, we only keep the values that are divisible by 2:
filtered = [i for i in range(20) if i%2==0]
print(filtered)
#output
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Control of memory in use by objects
I have also already mentioned sys.getsizeof() in the articles, but here I want to show you an interesting example that will show all the usefulness of memory control
import sys
mylist = range(0, 10000)
print(sys.getsizeof(mylist))
#output
48
Just 48 bytes? Seriously? The list is from 0 to 9999?
Yes, guys and why is this happening, I'll tell you now
The fact is that range only pretends to be a list, behaves like a list, but in fact, the range function returns a class and it certainly loads less memory.
For comparison, let's create a real list with the same range
import sys
myreallist = [x for x in range(0, 10000)]
print(sys.getsizeof(myreallist))
#output
87616
Agree, the numbers vary greatly, so it's not so useless to monitor memory.
Dataclasses
Since version 3.7, Python offers data classes. There are several advantages over regular classes or other alternatives, such as returning multiple values or dictionaries:
- a data class requires a minimal amount of code
- that you can compare data classes because there is "__ eq __"
- you can easily output a data class for debugging because you can use "__ repr __"
- data classes that require type hints, this reduces the likelihood of errors
Here is an example of a data class in action:
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.suit)
# 'hearts'
print(card)
#Card(rank='Q', suit='hearts')
Finding the most common value
A fairly simple and elegant example of searching for repetitions in a sequence
from collections import Counter
print(Counter('abracadabra').most_common(1))
#output
[('a', 5)]
print(Counter('abracadabra').most_common(2))
#output
[('a', 5), ('b', 2)]
print(Counter('abracadabra').most_common(3))
#output
[('a', 5), ('b', 2), ('r', 2)]
As an argument for Counter, you can pass, for example, list. This will also work.
Merging Dictionaries (Python 3.5+)
Starting with Python 3.5, it's easier to combine dictionaries:
dict1 = { 'a': 1, 'b': 2 }
dict2 = { 'b': 3, 'c': 4 }
merged = { **dict1, **dict2 }
print (merged)
#output
{'a': 1, 'b': 3, 'c': 4}
If there are overlapping keys, the keys from the first dictionary will be overwritten.
In Python 3.9, combining dictionaries becomes even cleaner. The above merge in Python 3.9 can be rewritten as:
dict1 = { 'a': 1, 'b': 2 }
dict2 = { 'b': 3, 'c': 4 }
merged = dict1 | dict2
print (merged)
#output
{'a': 1, 'b': 3, 'c': 4}
Conclusion
The use of some complex (to learn) mechanics in a programming language seems unnecessary to many novice programmers.
But have you ever wondered why more experienced developers use such mechanisms more often?. Simplicity for a beginner and simplicity for a professional are two completely different things. What seems complicated and cumbersome for a beginner is actually the simplest and lightest solution for a more experienced programmer. Each of you will come to these methods and solutions by yourself. Sooner or later. It's just that in our world today, you can learn everything. Let's learn properly!
Put on Heart if you liked it and you learned something new!
You can also follow ME to receive notifications about new interesting articles.
FAQ
I am a beginner, how should I learn Python?
Look into the following series:
Learning Python
Step by Step to Junior
Ideas
Can we cooperate with you?
If you have interesting projects and you need a python (web)developer, then you can contact me by mail or discord and LinkedIn for cooperation
Connect to me on
This content originally appeared on DEV Community and was authored by Vadim Kolobanov
Vadim Kolobanov | Sciencx (2021-11-21T05:33:37+00:00) A few useful Tricks in Python for Beginners. Retrieved from https://www.scien.cx/2021/11/21/a-few-useful-tricks-in-python-for-beginners/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.