
Photo via editor Chatgpt
# Entry
Working with Python means relying on many built -in functions, especially in the case of scientific tasks. Popular functions such as lenIN maxIN rangeetc., they are common in a set of scientist tools and useful in various situations. However, many built -in functions remain unrecognized because they are perceived as useless.
In this article, we will examine seven different built -in, which can be a joke, but in fact they are very useful in their applications. These built -in are different from ordinary code, but they will find their place in your work flow when you are aware of their usefulness.
Inquisitive? Let’s get it.
# 1 divmod Built -in function
Many people rarely employ divmod The built -in function and even knows that it exists. . divmod The built -in function returns two numbers: the result of the division of the floor and the module operation. This may seem useless because we can employ the syntax as a // b AND a % b Without the need for built -in, especially when we rarely need both results at the same time.
In real cases, we often need both results and want them to calculate them someday, to accelerate the process. Several divmod Applications – including time conversion, pagination, party and clever shortcut mathematics – show its usefulness.
Let’s see an example of employ:
total_seconds = 7132
minutes, seconds = divmod(total_seconds, 60)
hours, minutes = divmod(minutes, 60)
print(f"Time: {hours:02d}:{minutes:02d}:{seconds:02d}")
Where the exit is shown below:
With one function we can evenly divide the numbers, which is useful in many applications.
# 2 slice Built -in function
. slice The built -in function is used to separate or extract parts of the sequences, such as strings, letters or shorts. This may seem unnecessary because we can simply create an object such as obj[1:10:2].
However, strength slice The built -in function becomes apparent when you need to employ the same cutting rule in different objects. The function helps us maintain a coherent analysis logic and allows us to build data processing strategies.
Here is an example of implementation:
evens = slice(0, None, 2)
text = "abcdefghij"
print(text[evens])
The output is shown below:
. slice Built -in above shows that we can set a reusable rule to adopt each second character.
# 3 iter Built -in function
. iter The built -in function creates an iterator object, which processes the elements sequentially, one after the other. This may seem unnecessary because we already have the “True” and “Break” pattern. However, this is helpful because it allows for a cleaner code and a better structure in the data pipeline.
For example, we can employ iter To control the processing of streaming data:
import io
f = io.BytesIO(b"12345678")
for block in iter(lambda: f.read(3), b""):
print(block)
Where the exit is shown below:
# 4. memoryview Built -in function
. memoryview The built -in function creates a memory view object from internal data without copying. This may seem an unnecessary function that does not take place in the standard flow of Python’s work.
But memoryview The function becomes useful when handling immense binary data, because it allows users to access and modify without creating a recent object. For example, you can replace part of the data in the same memory without copying, as shown in the following code.
buf = bytearray(b"hello")
mv = memoryview(buf)
mv[0] = ord('H')
print(buf)
mv[:] = b"HELLO"
print(buf)
The output is shown below:
bytearray(b'Hello')
bytearray(b'HELLO')
The assignment takes place in the same memory, which is helpful in every performance sensitive to performance.
# 5. any Built -in function
. any The built -in function returns the logical value, checking the elements in the iterable object. Is coming back True If any element in iteral is true and False Otherwise. The function seems useless because it seems to replace a straightforward check loop.
However, strength any The function consists of its ability to avoid creating ephemeral objects and using a indolent assessment with generators, which means that the function can have a clear loop logic and reduce memory consumption.
An example of Python code is shown below:
files = ["report.txt", "sales.csv", "notes.md"]
print(any(f.endswith(".csv") for f in files))
Where the exit is shown below:
This is beneficial when we have cases of employ requiring validation or protection conditions.
# 6. all Built -in function
. all The built -in function is similar to anyBut the difference is that the first one returns only True If all Iteration objects are true. Similar to anyThe all The built -in function is often perceived as useless, because the manual loop can achieve the same result.
This is valuable built -in because it provides a declarative and miniature -circuit verification that each element is true with a indolent assessment of generators. This means that the code is cleaner and requires less memory.
An example of employ consists in using the following code:
required = ["id", "name", "email"]
record = {"id": 1, "name": "Ana", "email": "a@x.io"}
print(all(k in record for k in required))
Where the exit is shown below:
Applications include diagram checks and checking input correctness.
# 7. zip Built -in function
. zip The built -in function is used to aggregate elements from many iterative objects in shorts. This may seem unnecessary, because the programmer can simply engrave with indexes, for example for i in range(len(x)): The loop or because it returns only shorts.
. zip However, the built -in function is much more helpful, because it allows you to loit to many iterative objects without juggling indicators. Because the function creates couples only if necessary, it will not waste memory. He also avoids all joint index errors when we manually manage indexing.
Python’s example is shown below:
keys = ["id", "name", "email"]
vals = [1, "Ana", "a@x.io"]
record = dict(zip(keys, vals))
print(record)
Where the exit is shown below:
{'id': 1, 'name': 'Ana', 'email': 'a@x.io'}
There are many applications, for example in the case of parallel iteration in the field of data sets or couples calculations without index arithmetic.
# Application
Python is a useful programming language of any data related to data, and its built -in functions are a significant part of this usability. However, some built-in are perceived as useless-it means until you employ them and you don’t realize how valuable they are.
I hope it helped!
Cornellius Yudha Wijaya He is a data assistant and data writer. Working full -time at Allianz Indonesia, he loves to share Python and data tips through social media and media writing. Cornellius writes on various AI topics and machine learning.
