Mastering Python: 65 Essential Built-In Functions for Every Developer
Zaid Ullah
-- Python Developer | Backed Developer | Data Scientist | ML Engineer | AI | DL | NLP | WQU Student.
Let me introduce myself as an author who is deeply passionate about Python programming. I am on an exciting journey to create an article that showcases, The Top-65 Built-In Functions in Python.?
With my curiosity and understanding of the language, I am exploring the many features of Python’s library. Through my writing, I aim to make complex ideas easy to understand, capturing the interest of my readers and getting them excited about what Python can do.?
I am dedicated to providing clear and helpful explanations, empowering readers to make the most of Python’s Built-In Functions. Join me as I uncover the secrets of Python’s versatile toolkit, and together we can embark on a coding adventure. here
Python Programming: Python is a versatile and powerful programming language that offers a rich set of built-in functions. These functions serve as the building blocks of Python development, providing convenient and efficient ways to perform various tasks. here
I will provide concise explanations and practical code examples for each function, enabling you to enhance your Python skills and increase your productivity.
Why we use Build-In Functions?
We use build-in functions in program because it’s provide Reusability, Efficiency, Standardization, Simplification, Error handling & Extensibility.
What is Build-In Functions: Built-in functions in Python are pre-defined functions that come with the Python programming language. They offer a wide range of functionality and play a crucial role in Python programming.
In this article, I will explore the Top-65 Python Built-In Functions that are crucial for developers in any field.
The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.
A
number = -1972
absolute_value = abs(num)
print(absolute_value) # Output: 1972 or +1972
2. aiter (): Return an asynchronous iterator (aiter in Python 3.10) for an asynchronous iterable. Equivalent to calling ‘x.__aiter__()’.
Note: Unlike ‘iter()’, ‘aiter()’ has no 2-argument variant.
import asyncio
async def async_generator():
yield 1
yield 2
yield 3
async def main():
async_iter = aiter(async_generator())
async for item in async_iter:
print(item)
asyncio.run(main())
# Output: 1 2 3
3. all(): The ‘all()’ function returns ‘True’ if all elements in an iterable are true, and ‘False’ otherwise. It is the counterpart of the ‘any()’ function.
numbers = [1, 2, 3, 4, 5]
check = all(numbers)
print(check) # Output: True
4. any(): The ‘any()’ function returns ‘True’ if any element in an iterable is true, and ‘False’ otherwise. It is useful for checking the truthiness of elements.
numbers = [0, 1, 2, 3, 4]
check = any(numbers)
print(check) # Output: True
Or
numbers = [0] # numbers = []
check = any(numbers)
print(check) # Output: False
5. anext(): When awaited, return the next item from the given asynchronous iterator, or default if given and the iterator is exhausted.
This is the async variant of the next() Built-In, and behaves similarly.
This calls the __anext__() method of async_iterator, returning an awaitable. Awaiting this returns the next value of the iterator. If default is given, it is returned if the iterator is exhausted, otherwise StopAsyncIteration is raised.
import asyncio
async def async_generator():
yield 1
yield 2
yield 3
async def main():
async_iter = async_generator().__aiter__()
try:
while True:
item = await anext(async_iter)
print(item)
except StopAsyncIteration:
pass
asyncio.run(main())
# Output: 1 2 3
6. ascii(): As repr(), return a string containing a printable representation of an object, but escape the non-ASCII characters in the string returned by repr() using \x, \u, or \U escapes. This generates a string similar to that returned by repr() in Python 2.
text = "Café"
print(ascii(text)) # Output: 'Caf\xe9'
Or?
string = 'Héllo'
ascii_string = ascii(string)
print(ascii_string) # Output: 'H\xe9llo'
B
7. bin(): The ‘bin()’ function converts an integer to a binary string prefixed with "0b." It is useful for binary representation and bitwise operations.
x = 3
prin(bin(x)) # Output: 0b11
8. bool(): Return a Boolean value, i.e. one of True or False. x is converted using the standard truth testing procedure. If x is false or omitted, this returns False; otherwise, it returns True. The bool class is a subclass of int (see Numeric Types — int, float, complex). It cannot be subclassed further. Its only instances are False and True (see Boolean Values).
x = True
y = False
print(bool(x + y)) # Output: True
9. bytearry(): Return a new array of bytes. The bytearray class is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Bytearray Operations.
x = 10
print(bytearray(x)) # Output: bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
10. bytes(): Return a new ‘bytes’ object which is an immutable sequence of integers in the range ‘0 ≤ x < 256’. bytes is an immutable version of bytearray – it has the same non-mutating methods and the same indexing and slicing behavior.
x = 10
print(bytes(x))
# Output: b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
C
11. callable(): Return True if the object argument appears callable, False if not. If this returns ‘True’, it is still possible that a call fails, but if it is ‘False’, calling object will never succeed. Note that classes are callable (calling a class returns a new instance); instances are callable if their class has a ‘__call__()’ method.
def my_function():
print('Hello')
print(callable(my_function)) # Output: True
12. chr(): Return the string representing a character whose Unicode code point is the integer ‘i’. For example, ‘chr(97)’ returns the string ‘a’, while ‘chr(8364)’ returns the string '€'. This is the inverse of ord().
The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base 16). ValueError will be raised if ‘i’ is outside that range.
x = 12
print(chr(x)) # Output: ♀
# OR
character = chr(65)
print(character) # Output: 'A'
13. compileall(): The ‘compileall()’ function compiles all Python source files in a directory tree. It is used for batch compilation of Python modules
import compileall
compileall.compile_dir(r'C:\Users\zaid arman\Desktop\# Define an asynchronous iterable class.py')
14. complex(): The ‘complex()’ function creates a complex number with the specified real and imaginary parts. It is used for working with complex numbers and mathematical operations.
number = complex(2, 3)
print(number) # Output: (2+3j)
D
15. dict(): The ‘dict()’ function creates a dictionary or converts a sequence of key-value pairs into a dictionary. Dictionaries are fundamental for organizing and accessing data using keys.
Learner = dict(name="Zaid Ullah", age=24, grade="A")
print(Learner) # Output: {'name': 'Zaid Ullah', 'age': 20, 'grade': 'A'}
16. dir(): The ‘dir()’ function returns a list of valid attributes and methods for an object. It is useful for exploring the available functionality of an object.?
my_list = [1, 2, 3]
print(dir(my_list))
# Output:
"""
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__',
'__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__',
'__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__',
'__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__',
'__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append',
'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
'reverse', 'sort']
"""
17. divmod(): The ‘divmod()’ function takes two numbers as arguments and returns a tuple containing the quotient and remainder of their division.
result = divmod(10, 3)
print(result) # Output: (3, 1)
E
18. enumerate(): The ‘enumerate()’ function adds a counter to an iterable object and returns an enumerate object. It is commonly used in loops to obtain both the index and value of each item.
Friends = ['Zaid', 'Arman', 'Khan']
for index, frndlist in enumerate(Friends):
print(index, frndlist)
# Output:
'''
0 Zaid
1 Arman
2 Khan
'''
19. eval(): The ‘eval()’ function evaluates a string as a Python expression and returns the result. It is commonly used for dynamic evaluation of code.
expression = '2 + 3 * 4'
result = eval(expression)
print(result) # Output: 14
20. exec(): The ‘exec()’ function dynamically executes Python code stored in a string or code object. It is used for evaluating and executing dynamic code.
code = '''
for i in range(5):
print(i)
'''
exec(code) # Output: 0 1 2 3 4
F
21. filter(): The ‘filter()’ function creates an iterator from elements of an iterable for which a given function returns ‘True’. It is used to selectively filter out items based on a condition.
def is_even(x):
return x % 2 == 0
numbers = [1, 2, 3, 4, 5]
even_numbers = filter(is_even, numbers)
for num in even_numbers:
print(num) # Output: 2 4
22. float(): The ‘float()’ function converts a value into a floating-point number. It is helpful for handling decimal numbers or converting string representations of floats.
pi_value = float("3.141579")
print(pi_value) # Output: 3.141579
grade = float(98)
print(grade) # # Output: 98.0
23. format(): The ‘format()’ function formats a string by replacing placeholders with values. It provides flexible string formatting options.
name = 'Zaid Ullah'
age = 24
message = 'My name is {} and I am {} years old.'.format(name, age)
print(message) # Output: My name is Zaid Ullah and I am 24 years old.
24. frozenset(): The ‘frozenset()’ function returns an immutable frozenset object. It is similar to a set, but its elements cannot be modified after creation.
my_set = frozenset([1, 2, 3])
print(my_set) # Output: frozenset({1, 2, 3})
G
25. getattr(): The ‘getattr()’ function returns the value of a named attribute of an object. It is useful for dynamically accessing object attributes.
class Person:
name = 'Khan'
person = Person()
print(getattr(person, 'name')) # Output: 'Khan'
26. globals(): The ‘globals()’ function returns a dictionary containing the current global symbol table. It is used to access and manipulate global variables.
x = 10
def my_function():
global x
x = 5
my_function()
print(x) # Output: 5
H
27. hasattr(): The ‘hasattr()’ function checks if an object has a specified attribute and returns a boolean value. It is used for attribute existence testing.
class Person:
name = 'Zaid'
person = Person()
print(hasattr(person, 'name')) # Output: True
28. hash(): The ‘hash()’ function returns the hash value of an object. It is commonly used to check object uniqueness and for dictionary operations
value = hash('hello Zaid')
print(value) # Output: 4322554999407990986
29. help(): The ‘help()’ function displays documentation and information about Python objects, modules, functions, etc. It provides useful information for understanding and using Python elements.
help(dict)
# Output:
'''
Help on class dict in module builtins:
class dict(object)
| dict() -> new empty dictionary
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
| dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
-- More --
'''
Or?
help(list)
# Output:
'''
Help on class list in module builtins:
class list(object)
| list(iterable=(), /)
|
| Built-in mutable sequence.
|
| If no argument is given, the constructor creates a new empty list.
| The argument must be an iterable if specified.
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
-- More --
'''
30. hex(): The ‘hex()’ function converts an integer to a lowercase hexadecimal string prefixed with '0x'. It is helpful for working with hexadecimal representations.
value = 255
hex_value = hex(value)
print(hex_value) # Output: '0xff'
I
31. id(): The ‘id()’ function returns the unique identifier of an object. It is useful for checking object identity or memory addresses.
领英推荐
number = 1
print(id(number)) # Output: 140711405675304
number = 12
print(id(number)) # Output: 140711405675656
32. input(): The ‘input()’ function reads user input from the console. It allows you to interact with your Python programs and gather information from the user.
Name = input(" Enter Your Name: ")
Nge = input(" Enter Your Age: ")
print("Hello, your name is " + Name + "!")
print(" & you are " + Age + " year old")
33. int(): The ‘int()’ function converts a value into an integer. It is useful for converting user input or parsing numerical data.
number = int("10")
print(number) # Output: 10
number_2 = int(9.4)
print(number_2) # Output: 9
34. isinstance(): The ‘isinstance()’ function checks if an object is an instance of a specified class or any of its subclasses. It helps with type checking and object validation.
Name = "Zaid"
check = isinstance(Name, str)
print(check) # Output: True
Age = 24
check = isinstance(Age, int # not str)
print(check) # Output: True
35. issubclass(): The ‘issubclass()’ function checks if a class is a subclass of another class and returns a boolean value. It is used for class hierarchy testing.
class Person:
pass
class Student(Person):
pass
print(issubclass(Student, Person)) # Output: True
36. iter(): The ‘iter()’ function returns an iterator object for an iterable. It is commonly used in loops and iterations.
my_list = [1, 2, 3]
my_iterator = iter(my_list)
print(next(my_iterator)) # Output: 1
L
37. len(): The ‘len()’ function returns the length of a string, list, or any other iterable object. It is handy for determining the size of a collection or the number of characters in a string.
Zaid_list = [1, 2, 3, 4, 5, 6]
print(len(Zaid_list)) # Output: 6
38. list(): The ‘list()’ function creates a list from an iterable object or converts a string into a list of characters. It is widely used for data manipulation and storage.
numbers = list(range(1, 10))
print(numbers) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
39. local(): The ‘local()’ function returns a dictionary containing the current local symbol table. It is used to access and manipulate local variables within a function.
def my_function():
x = 5
print(locals())
my_function() # Output: {'x': 5}
M
40. map(): The ‘map()’ function applies a given function to each item in an iterable and returns an iterator of the results. It is useful for performing operations on each element of a collection.
def square(x):
return x ** 2
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(square, numbers)
for num in squared_numbers:
print(num) # output: 1 4 9 16 25
41. max(): The ‘max()’ function returns the largest item in an iterable or the maximum of multiple arguments. It is commonly used for finding the maximum value in a collection.
numbers = [54, 27, 92, 16, 7]
max_number = max(numbers)
print(max_number) # Output: 92
42. min(): The ‘min()’ function returns the smallest item in an iterable or the minimum of multiple arguments. It is the counterpart of the ‘max()’ function.
numbers = [54, 27, 92, 16, 7]
max_number = min(numbers)
print(max_number) # Output: 7
N
43. next(): The ‘next()’ function retrieves the next item from an iterator. It is used in conjunction with the ‘iter()’ function.
my_list = [1, 2, 3]
my_iterator = iter(my_list)
print(next(my_iterator)) # Output: 1
O
44. oct(): The ‘oct()’ function converts an integer to an octal (base 8) string prefixed with '0o'. It is useful for working with octal representations.
Age = 1999
oct_value = oct(Age)
print(oct_value) # Output: 0o3717
45. open(): The ‘open()’ function opens a file and returns a file object that can be used for reading, writing, or appending data. It is the primary function for working with files in Python.
file = open("data.txt", "r")
content = file.read()
print(content)
file.close()
46. ord(): The ‘ord()’ function returns an integer representing the Unicode character. It is the inverse of the ‘chr()’ function.
code = ord('A')
print(code) # Output: 65
P
47. pow(): The ‘pow()’ function raises a number to a specified power. It is an alternative to using the ‘**’ operator.
result = pow(2, 3)
print(result) # Output: 8
48. print(): The ‘print()’ function is used to output text or objects to the console. It is an indispensable tool for debugging and displaying information during program execution.
print(" Hello Zaid, Python is Awesome ")
49. property(): The 'property()' return a property attribute.
class C:
def __init__(self):
self._x = None
def getx(self):
return self._x
def setx(self, value):
self._x = value
def delx(self):
del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")
print(x) # Output: <property object at 0x000002A98D4CA890>
R
50. range(): The ‘range()’ function generates a sequence of numbers within a specified range. It is commonly used for looping/iterating over a sequence of values.
for i in range(1, 6):
print(i)
51. reversed(): The ‘reversed()’ function returns a reversed iterator of a sequence. It is commonly used for iterating over a sequence in reverse order.
numbers = [1, 2, 3, 4, 5]
reversed_numbers = reversed(numbers)
for number in reversed_numbers:
print(number)# Output: 5 4 3 2 1
52. reduce(): The ‘reduce()’ function applies a rolling computation to pairs of elements from an iterable, reducing it to a single value. It is part of the ‘functools’ module.
from functools import reduce
def add(x, y):
return x + y
numbers = [1, 2, 3, 4, 5]
total = reduce(add, numbers)
print(total) # Output: 165
53. repr(): The ‘repr()’ function returns a string representing a printable version of an object. It is used for obtaining a string representation that can be used to recreate the object.
x = [1, 2, 3]
representation = repr(x)
print(representation) # Output: [1, 2, 3]
54. round(): The ‘round()’ function rounds a number to a specified precision or to the nearest whole number. It is commonly used for decimal rounding.
Value_1 = 4.5
Value_2 = 5.5
rounded_1 = round(Value_1) # example 1
rounded_2 = round(Value_2) # example 2
print(rounded_1) # Output: 4
print(rounded_2) # Output: 6
In the above examples, the one(example 1) round down, and the other (example 2) round up. But still the rule should be the same all the time. right?
Apparently, it was like that until Python3. but then they changed to a logic called “Banker’s rounding”.
How: The idea is simple: if we always round up, on hundreds of millions of calculations It ends up significantly biasing the result.
Python3 (Version 3.0) and later eliminates this bias.
S
55. set(): The set() function creates a set or converts an iterable into a set. Sets are useful for storing unique elements and performing set operations.
Zaid_Set = set([1, 2, 2, 3, 3, 4])
print(Zaid_Set) # Output: {1, 2, 3, 4}
56. setattr(): The ‘setattr()’ function sets the value of a named attribute of an object. It is used for dynamically modifying object attributes.
class Person:
name = 'Arman'
person = Person()
setattr(person, 'name', 'Zaid')
print(person.name) # Output: 'Zaid'
57. sorted(): The ‘sorted()’ function returns a new sorted list from the items in an iterable. It is handy for sorting collections in ascending order.
numbers = [5, 2, 9, 1, 7]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 2, 5, 7, 9]
58. str(): The ‘str()’ function converts a value into a string. It is used to manipulate and concatenate textual data.
age = 25.0
print("I am " + str(age) + " years old") # output: I am 25 years old
59. super(): The ‘super()’ function returns a temporary object of a superclass, allowing you to call methods and access attributes from the parent class. It is typically used in inheritance scenarios.
class Parent:
def hello(self):
print('Hi, Parents!')
class Child(Parent):
def hello(self):
super().hello()
print('Hi, Child!')
child = Child()
child.hello()
# Output:
# Hi, Parents!
# Hi, Child!
60. sum(): The ‘sum()’ function returns the sum of all elements in an iterable. It is useful for calculating the total of a collection of numbers.
numbers = [11, 22, 33, 44, 55]
total = sum(numbers)
print(total) # Output: 165
T
61. tuple(): The ‘tuple()’ function creates a tuple object from an iterable. It is used for converting other iterables like lists or strings into tuples.
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple) # Output: (1, 2, 3)
62. type(): The ‘type()’ function is used to determine the type of an object. It helps you understand the nature of variables and aids in type checking
x = 10
print(type(x)) # Output: <class 'int'>
V
63. vars(): The ‘vars()’ function returns the ‘__dict__’ attribute of an object, or a dictionary representing the current local symbol table if called without arguments. It is used for accessing the attributes or variables of an object.
class MyClass:
x = 5
obj = MyClass()
print(vars(obj)) # Output: {}
Z
64. zip(): The ‘zip()’ function takes iterables as arguments and returns an iterator of tuples, where each tuple contains the corresponding elements from the iterables. It is often used for iterating over multiple lists simultaneously.
Names = ["Zaid", "Arman", "Khan"]
Ages = [24, 22, 25]
zipped_data = zip(Names, Ages)
for Name, Age in zipped_data:
print(Name, Age)
65. __import__(): The ‘__import__()’ function dynamically imports a module by name. It is a low-level function used for advanced import operations.
module_name = 'math'
math_module = __import__(module_name)
print(math_module.sqrt(81)) # Output: 9.0
If you find this article helpful?. Please follow me by clicking. here
Follow For More Interesting Articles:?
Corporate Accountant || Remote Bookkeeper || Financial Reporter
1 年Islamophobia Islamophobia is a form of prejudice or discrimination against Muslims that is often based on negative stereotypes and fear. It can manifest itself in a variety of ways, including verbal abuse, physical violence, and discrimination in employment, housing, and education. Islamophobia is a serious problem that has a negative impact on Muslims around the world. It can make it difficult for Muslims to live their lives freely and safely, and it can contribute to a climate of fear and hatred. READ FULL ARTICLE HERE: https://medium.com/@noah80257/islamophobia-b65598bc4b1a