python
February 10, 2024

Python Built-in Functions reference

In this small article, we will try to study as much as possible Built-in functions of Python. Here is the Python official documentation on the subject:

https://docs.python.org/3/library/functions.html

πŸ‘‰abs(x) - absolute value of a number. Everyone knows it, right :)

πŸ‘‰all(iterable) - returns True if all elements of the iterable object (list, tuple, dictionary) are True, otherwise returns False. Equivalent to:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

πŸ‘‰any() - returns True if any item in an iterable object are true, otherwise it returns False. Equivalent to:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

πŸ‘‰ascii(object) - returns a readable version of an object. Replaces none-ascii characters with escape character.

x = ascii("Hi SΓ₯m!")
print(x)

# Output: Hi S\e5m!

πŸ‘‰bin(x) - Return the binary version of the number.

binary_number = bin(20)
print(binary_number)

# 0b10100

πŸ‘‰bool(object) - returns the boolean value of a specified object. The function returns False if:

  • The object is empty, like [], {}, ()
  • The object is False
  • The object is 0
  • The object is None

Otherwise, it returns True. Keep in mind that, using negative number also returns True:

print(bool(-4))

# True

πŸ‘‰bytearray() -

πŸ‘‰bytes() -

πŸ‘‰callable(object) - returns True if the specified object is callable, otherwise it returns False.

def func():
    return 5

print(callable(func))

# True

When it returns False? Variables are not callable, for example.

πŸ‘‰chr(x) - converts an integer to its unicode character and returns it.

print(chr(97))
# a

πŸ‘‰compile() -

πŸ‘‰eval() -

πŸ‘‰exec() -

πŸ‘‰classmethod() - converts the method into class method. In newer versions of Python, it is used as decorator, like @classmethod.

class Student:
  marks = 0

  def compute_marks(self, obtained_marks):
    marks = obtained_marks
    print('Obtained Marks:', marks)

# convert compute_marks() to class method
Student.print_marks = classmethod(Student.compute_marks)

πŸ‘‰complex(real, imaginary) - returns a complex number object by taking real and imaginary parts as floats.

print(complex(2.3, 5.4))
# (2.3 + 5.4j)

In addition, we can convert strings to complex numbers, but in this case we should omit the second parameter:

print(complex("2+3j"))
# (2+3j)

πŸ‘‰delattr(object, name) - removes an attribute of an Object (if the object allows it).

class Coordinate:
  x = 10
  y = -5
  z = 0

point1 = Coordinate()
print('x = ',point1.x)
print('y = ',point1.y)
print('z = ',point1.z)

delattr(Coordinate, 'z')

# Raises Error
print('z = ',point1.z)

πŸ‘‰dict(**kwarg) - does not return any value. Instead, it creates a new dictionary according to keyword arguments given to it. Let's consider various ways of doing so:

numbers = dict(x=5, y=0)
print('numbers =', numbers)

# numbers = {'y':0, 'x':5}
numbers = dict([('x', 5), ('y', -5)])
print('numbers =',numbers)

# numbers = {'y':-5, 'x':5}

Also, we can create an empty dictionary:

print(dict())

# {}

πŸ‘‰dir(object) - returns the list of valid attributes of the passed object.

πŸ‘‰divmod(num1, num2) - takes two numbers as arguments and returns their quotient and remainder in a tuple.

result = divmod(8, 3)
print('Quotient and Remainder = ',result)

# Output: Quotient and Remainder =  (2, 2)

πŸ‘‰enumerate(iterable, start=0) - adds a counter to an iterable and returns it as an enumerate object (iterator with index and the value).

langs = ['Uzbek', 'English', 'Turkish']
enum_langs = enumerate(langs)
print(list(enum_length))

# [(0, 'Uzbek'), (1, 'English'), (2, 'Turkish')]

Keep in mind that, when printing always convert the result to list, since the function returns enumerate object.

πŸ‘‰staticmethod() - converts the given method of an object to static method.

class Calculator:
  def add_numbers(num1, num2):
    return num1 + num2

Calculator.add_numbers = staticmethod(Calculator.add_numbers)
sum = Calculator.add_numbers(5, 7)
print('Sum:', sum)

# Output: Sum: 12

πŸ‘‰filter(function, iterable) - selects elements from an iterable based on the result of a given function.

def check_even(number):
    if number % 2 == 0:
          return True  
    return False

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers_iterator = filter(check_even, numbers)
even_numbers = list(even_numbers_iterator)
print(even_numbers)

# Output: [2, 4, 6, 8, 10]

πŸ‘‰float() - returns a floating point number from a number or a string.

πŸ‘‰format(value, format_spec) - returns a formatted value based on the specified formatter. It can be 'b' - binary, 'd' - decimal or some other. You can find on doc.

val = 0xf3
bval = format(val, 'b')
dval = format(val, 'd')
print(bval, dval)

# 11110011 243

πŸ‘‰frozenset(iterable) - frozen set is just an immutable version of a Python set object. While elements of a set can be modified at any time, elements of the frozen set remain the same after creation.

Due to this, frozen sets can be used as keys in Dictionary or as elements of another set. But like sets, it is not ordered (the elements can be set at any index).

mylist = ['apple', 'banana', 'cherry']
x = frozenset(mylist)
print(x)

# frozenset({'apple', 'cherry', 'banana'})

πŸ‘‰getattr(object, name) - returns the value of the named attribute of an object. If not found, it returns the default value provided to the function.

class Student:
  marks = 88
  name = 'Sheeran'

person = Student()
name = getattr(person, 'name')
print(name)
marks = getattr(person, 'marks')
print(marks)

# Sheeran
# 88

πŸ‘‰globals() - returns a dictionary with all the global variables and symbols for the current program.

πŸ‘‰hasattr() - returns true if an object has the given named attribute and false if it does not.

class Person:
    age = 23
    name = "Adam"

person = Person()
print("Person's age:", hasattr(person, "age"))
print("Person's salary:", hasattr(person, "salary"))

# Person's age: True
# Person's salary: False

πŸ‘‰help() - use it when you need some help.

πŸ‘‰hex(int) - converts an integer to the corresponding hexadecimal number in string form and returns it.

num = 45
print(hex(num))

# 0x2d

πŸ‘‰hash(object) - returns the hash value of an object if it has one.

text = 'Python Programming'
hash_value = hash(text)
print(hash_value)

# Output: -966697084172663693

πŸ‘‰input('prompt') - takes input from the user and returns it.

πŸ‘‰id() - returns the β€œidentity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

In other words, this is the address of the object in memory.

print("id of 5 =", id(5))

# 140472391630016

πŸ‘‰isinstance(object, classinfo) - checks if the object (first argument) is an instance or subclass of classinfo class (second argument).

numbers = [1, 2, 3, 4, 2, 5]
result = isinstance(numbers, list)
print(result)

# Output: True

πŸ‘‰int(x) - converts a number or a string to its equivalent integer.

πŸ‘‰issubclass(class, classinfo) - checks whether the given class is subclass of classinfo.

class Polygon:
  def __init__(polygonType):
    print('Polygon is a ', polygonType)

class Triangle(Polygon):
  def __init__(self):

    Polygon.__init__('triangle')
    
print(issubclass(Triangle, Polygon))
print(issubclass(Triangle, list))
print(issubclass(Triangle, (list, Polygon)))
print(issubclass(Polygon, (list, Polygon)))

# True
# False
# True
# True

Take into account that every class is considered subclass of itself.

πŸ‘‰iter() - returns an iterator for the given argument.

πŸ‘‰next() - returns the next item from the iterator.

πŸ‘‰list(iterable) - returns a list in Python.

text = 'Python'
print(list(text))
print(type(text_list))

# ['P', 'y', 't', 'h', 'o', 'n']
# <class 'list'> 

πŸ‘‰locals() - returns a dictionary with all the local variables and symbols for the current program.

πŸ‘‰len(iterable) - returns the number of items (length) in an object.

πŸ‘‰max(iterable) - returns the largest item in an iterable.

πŸ‘‰min(iterable) - returns the smallest item in an iterable.

πŸ‘‰memoryview() - is a safe way to expose the buffer protocol in Python.

Python Buffer Protocol - the buffer protocol provides a way to access the internal data of an object. This internal data is a memory array or a buffer.

The buffer protocol allows one object to expose its internal data (buffers) and the other to access those buffers without intermediate copying.

This protocol is only accessible to us at the C-API level and not using our normal codebase.

So, in order to expose the same protocol to the normal Python codebase, memory views are present.

https://www.programiz.com/python-programming/methods/built-in/memoryview

πŸ‘‰map(function, iterables) - executes a given function to each element of an iterable (such as lists, tuples, ...)

numbers = [1,2,3,4]

def square(number):
  return number * number

squared_numbers = map(square, numbers)

result = list(squared_numbers)
print(result)

# Output: [1,4,9,16]

Keep in mind that, after applying this function, you have to convert the result into list or some other alternative type, since by default it returns map object.

πŸ‘‰object() - returns a featureless object.

πŸ‘‰oct(int) - returns an octal string from the given integer number.

# decimal to octal
print('oct(10) is:', oct(10))

# 0o12

πŸ‘‰ord() - returns an integer representing the Unicode character.

character = 'P'
unicode_char = ord(character)
print(unicode_char)

# Output: 80

πŸ‘‰open(file) - returns a file object which can used to read, write and modify the file. If the file is not found, it raises the FileNotFoundError exception.

f = open("path_to_file", mode = 'r', encoding='utf-8')

πŸ‘‰pow() - computes the power of a number.

print(pow(3, 4))
# Output:  81

πŸ‘‰print() - Used to write "Hello World!" on the screen :))

πŸ‘‰property() - returns the property attribute from the given getter, setter, and deleter. (It is actually a decorator)

πŸ‘‰range() - generates a sequence of numbers. By default, the sequence starts at 0, increments by 1, and stops before the specified number.

nums = range(4)
for i in nums:
    print(i, end=" ")
    
# 0 1 2 3

πŸ‘‰repr(object) - returns a printable representation of the given object.

πŸ‘‰reversed() - computes the reverse of a given sequence object and returns it in the form of a list.

seq = 'Python'ng
print(list(reversed(seg)))

# Output: ['n', 'o', 'h', 't', 'y', 'P']

πŸ‘‰round(number) - rounds a number to the nearest integer.

πŸ‘‰set() - creates a set from an iterable object.

print(set([1,2,3]))

# {1,2,3}

πŸ‘‰setattr() - sets the value of the attribute of an object.

class Student:
  marks = 88
  name = 'Sheeran'

person = Student()
setattr(person, 'name', 'Adam')
setattr(person, 'marks', 78)

print(person.name)
print(person.marks)

# Adam
# 78

πŸ‘‰slice() - returns a slice object that is used to slice any sequence (string, tuple, list, range, or bytes).

text = 'Python Programing'

sliced_text = slice(6)
print(text[sliced_text])

# Output: Python

https://www.programiz.com/python-programming/methods/built-in/slice

πŸ‘‰sorted(iterable) - sorts the elements of the given iterable in ascending order and returns it.

πŸ‘‰str(object) - returns the string representation of a given object.

πŸ‘‰sum(iterable) - adds the items of an iterable and returns the sum.

πŸ‘‰tuple(iterable) - creates a tuple from a given iterable object.

πŸ‘‰type() - either returns the type of the object or returns a new type object based on the arguments passed.

πŸ‘‰vars() - returns the __dict__ (dictionary mapping) attribute of the given object.

πŸ‘‰zip(*iterables) - takes iterables (can be zero or more), aggregates them in a tuple, and returns it.

languages = ['Java', 'Python', 'JavaScript']
versions = [14, 3, 6]

result = zip(languages, versions)
print(list(result))

# Output: [('Java', 14), ('Python', 3), ('JavaScript', 6)]

That's all.


So, today we considered 66 out of 68 built-in functions in Python. I admit that some of them are highlighted and even without description, but that's not reasonless. Some methods need more thorough research and usage cases to grasp the whole meaning and hence I just highlighted them. Next time, I try to cover them as well on separate articles.

🏁 Enough for today, thanks for your attention!