Python is a powerful and versatile programming language that comes with many built-in functions that can perform various tasks. In this blog, I will introduce some of the most common and useful Python built-in functions and show you how to use them with examples.
What are Python built-in functions?
Python built-in functions are functions that are defined in the Python interpreter and are always available for use without importing any modules. They are part of the Python standard library and provide basic functionality such as arithmetic operations, type conversions, input/output, iteration, etc.
You can find the complete list of Python built-in functions in the official documentation. Here are some of the characteristics of Python built-in functions:
- They are written in lowercase letters and may have underscores (_) to separate words. For example,
print
,len
,abs
, etc. - They can take zero or more arguments and return a value or None. For example,
print
takes any number of arguments and returns None, whilelen
takes one argument and returns an integer. - They can be called by using parentheses () after the function name and passing the arguments inside the parentheses. For example,
print("Hello, world!")
,len([1, 2, 3])
, etc. - They can be assigned to variables or passed as arguments to other functions. For example,
f = abs
,map(str, [1, 2, 3])
, etc.
Some examples of Python built-in functions
Let’s see some examples of how to use some of the most common and useful Python built-in functions.
abs()
The abs()
function returns the absolute value of a number. The argument can be an integer, a floating-point number, or an object that implements the __abs__()
method. If the argument is a complex number, its magnitude is returned.
For example:
>>> abs(-5)
5
>>> abs(3.14)
3.14
>>> abs(1 + 2j)
2.23606797749979
all()
The all()
function returns True if all elements of an iterable are true (or if the iterable is empty). An iterable is an object that can be looped over, such as a list, a tuple, a string, a dictionary, a set, etc. A value is considered true if it is not False, None, zero, or an empty object.
For example:
>>> all([True, 1, "a"])
True
>>> all([True, 0, "a"])
False
>>> all([])
True
any()
The any()
function returns True if any element of an iterable is true. If the iterable is empty, it returns False. It is the opposite of the all()
function.
For example:
>>> any([False, 0, ""])
False
>>> any([False, 1, ""])
True
>>> any([])
False
ascii()
The ascii()
function returns a string containing a printable representation of an object, but escapes the non-ASCII characters in the string returned by repr()
using \x
, \u
, or \U
escapes. This is useful for displaying an object that may contain non-ASCII characters in a readable way.
For example:
>>> ascii("Hello")
'Hello'
>>> ascii("こんにちは")
"'\\u3053\\u3093\\u306b\\u3061\\u306f'"
bin()
The bin()
function converts an integer number to a binary string prefixed with “0b”. The result is a valid Python expression. If the argument is not an integer, it has to define an __index__()
method that returns an integer.
For example:
>>> bin(10)
'0b1010'
>>> bin(-5)
'-0b101'
>>> bin(3.14)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer
bool()
The bool()
function returns the boolean value of the specified object. It converts the object to True or False using the standard truth testing procedure. A value is considered true if it is not False, None, zero, or an empty object.
For example:
>>> bool(True)
True
>>> bool(0)
False
>>> bool("")
False
>>> bool([1])
True
bytearray()
The bytearray()
function returns a bytearray object that is a mutable sequence of integers in the range 0 <= x < 256. It can be used to manipulate binary data.
For example:
>>> bytearray(b"Hello")
bytearray(b'Hello')
>>> bytearray([65, 66, 67])
bytearray(b'ABC')
>>> bytearray(5)
bytearray(b'\x00\x00\x00\x00\x00')
bytes()
The bytes()
function returns a bytes object that is an immutable sequence of integers in the range 0 <= x < 256. It can be used to represent binary data.
For example:
>>> bytes(b"Hello")
b'Hello'
>>> bytes([65, 66, 67])
b'ABC'
>>> bytes(5)
b'\x00\x00\x00\x00\x00'
callable()
The callable()
function returns True if the specified object is callable, otherwise False. A callable object is an object that can be called like a function, such as a function, a method, a class, etc.
For example:
>>> callable(print)
True
>>> callable(len)
True
>>> callable(42)
False
>>> callable(str.upper)
True
chr()
The chr()
function returns a character from the specified Unicode code. The argument must be an integer in the range 0 <= x <= 0x10FFFF.
For example:
>>> chr(65)
'A'
>>> chr(97)
'a'
>>> chr(128512)
'😀'
classmethod()
The classmethod()
function converts a method into a class method. A class method is a method that is bound to a class rather than an instance of the class. It can be called on the class itself or on an instance of the class. The first parameter of a class method is the class itself, usually named cls.
For example:
class Person:
count = 0 # class attribute
def __init__(self, name):
self.name = name # instance attribute
Person.count += 1 # increment the class attribute
@classmethod
def get_count(cls): # class method
return cls.count # return the class attribute
p1 = Person("Alice")
p2 = Person("Bob")
print(Person.get_count()) # call the class method on the class
print(p1.get_count()) # call the class method on an instance
Output:
2
2
compile()
The compile()
function returns the specified source as an object, ready to be executed. The source can be a string, a byte sequence, or an AST object. The filename argument should give the file from which the code was read; pass some recognizable value if it wasn’t read from a file. The mode argument specifies what kind of code must be compiled; it can be ‘exec’ (for statements), ‘eval’ (for expressions), or ‘single’ (for a single interactive statement). The flags and dont_inherit arguments affect future statements and are explained in detail in the documentation.
For example:
>>> code = "x = 10\ny = 20\nprint(x + y)"
>>> obj = compile(code, "demo", "exec")
>>> obj
<code object <module> at 0x000001F9E8C3B030, file "demo", line 1>
>>> exec(obj)
30
complex()
The complex()
function returns a complex number. A complex number is a number that can be expressed in the form a + bj, where a and b are real numbers and j is the imaginary unit. The argument can be a string, a number, or two numbers separated by a comma.
For example:
>>> complex(1)
(1+0j)
>>> complex(1, 2)
(1+2j)
>>> complex("3+4j")
(3+4j)
delattr()
The delattr()
function deletes the specified attribute (property or method) from the specified object. The attribute name must be a string. This is equivalent to using del obj.attr
.
For example:
class Person:
def __init__(self, name):
self.name = name
p = Person("Alice")
print(p.name) # Alice
delattr(p, "name") # delete the name attribute
print(p.name) # AttributeError: 'Person' object has no attribute 'name'
dict()
The dict()
function returns a dictionary (array). A dictionary is an unordered collection of key-value pairs. The keys must be immutable objects such as strings, numbers, or tuples. The values can be any objects.
For example:
>>> dict(a=1, b=2, c=3) # using keyword arguments
{'a': 1, 'b': 2, 'c': 3}
>>> dict([(1, "one"), (2, "two"), (3, "three")]) # using a list of tuples
{1: 'one', 2: 'two', 3: 'three'}
>>>dict({4: "four", 5: "five", 6: "six"}) # using a dictionary
{4: 'four', 5: 'five', 6: 'six'}
Conclusion
In conclusion, these examples represent just a glimpse into the rich world of Python’s built-in functions. Python’s extensive collection of built-in functions serves various purposes and can significantly simplify many common programming tasks. Whether you’re a beginner or an experienced developer, these functions are powerful tools in your coding arsenal.
To delve deeper into Python’s built-in functions and discover more ways they can enhance your programming endeavors, I encourage you to explore the comprehensive list provided in the official Python documentation.
If you found this tutorial helpful, stay tuned for more from Fluidstrap.
Check out our latest blogs on WordPress, web development, AI, and more.
Explore our 16 free online tools for SEO optimization and more.
Thanks for Reading! 😊