Home
About Us Privacy Policy
 

BUILT-IN METHODS IN PYTHON

ADVERTISEMENT

Advanced Built-In



What are Pythons' built-in functions, and why use them?

During development, developers face situations of repetitive patterns of problems. One solution is they implement the functions to solve the issues themselves, but this would defeat the purpose of programming in a high-level programming language like Python.

Another issue is that the developers might have a bug in the implementation, ultimately leading to unstable software. Hence, Python developers have provided a set of functions to avoid the re-implementation of common functions.


abs()

Python's in-built abs() method should be used when you want the absolute value of an int type.

print(abs(-1234.5677))
print(abs(1234))
print(abs(-1234))

1234.5677
1234
1234


all()

This in-built all() method in Python will return True when all the elements of an iterable type evaluate to True. Any non-zero, non-None value evaluates to True.

print(all((0, 1, 2, 3, 4)))
print(all((1, 2, 3, 4, 5.678)))

False
True


any()

This in-built any() method in Python will return True even if one item in the iterable evaluates to True. Any non-zero, non-None value evaluates to True.

print(any((0, 0, 0, 0, 1)))

True


ascii()

This in-built method ascii() in Python will return the ASCII printable version of the text. It will escape any non-ascii character.

print(ascii("Hello, Juan Daniél"))

'Hello, Juan Dani\xe9l'


bin()

This in-built method bin() in Python will return the binary representation of an integer.

print(bin(8))

0b1000


bool()

This in-built bool() method in Python will return the boolean representation of an object.

print(bool(0))
print(bool(1))
print(bool({}))

False
True
False


bytearray()

This in-built bytearray() method in Python will return an array of bytes.

print(bytearray("ABCD".encode("UTF-8")))

bytearray(b'ABCD')


bytes()

This in-built bytes() method in Python will return a bytes object.

print(bytes("ABCD".encode("UTF-8")))

b'ABCD'


callable()

This in-built callable() method in Python will return the boolean value of True if the specified object is callable; otherwise, it will return a False.

def foo():
    print("This is a callable method")

print(callable(foo))

True


chr()

This in-built chr() method in Python will return a character from specified Unicode characters.

print(chr(65))

A


ADVERTISEMENT

classmethod()

This in-built classmethod() method in Python will convert a function into a method that can access class properties and methods. It will become another class method.

class MyRandomTestClassForDemonstration:
    value = 28

    def foo(cls):
        print(cls.value)

MyRandomTestClassForDemonstration.foo = classmethod(MyRandomTestClassForDemonstration.foo)

MyRandomTestClassForDemonstration.foo()

28


compile()

This in-built compile() method in Python will return the code object.

code = compile('print(8)', '_', 'eval')
exec(code)

8

You can read more about the compile method here.


complex()

This in-built complex() method in Python will return a complex number.

print(complex(1.23))

(1.23+0j)


delattr()

Python's in-built delattr() method will delete the specified attribute, either a property or a method, from the object.

class Person:
    def __init__(self, name):
        self.name = name

person = Person("John")
print(person.name)
delattr(person,'name')
try:
    print(person.name)
except AttributeError as e:
    print(e)

John
'Person' object has no attribute 'name'


dict()

This in-built dict() method in Python will return a dictionary.

person = dict(name="John", age=46)
print(person)

{'name': 'John', 'age': 46}


dir()

This in-built dir() method in Python will return a list of specified object methods and properties.

class Person:
    def __init__(self, name):
        self.name = name

print(dir(Person))

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']


ADVERTISEMENT

divmod()

This in-built divmod() method in Python will return the quotient and remainder when args1 is divided by args2.

print(divmod(5, 2))

(2, 1)


enumerate()

This in-built enumerate() in Python takes a collection and returns the same as an enumerate object.

cars = ('Toyota', 'Audi', 'Mercedes-Benz')
cars = enumerate(cars)
for car in cars:
    print(car)

(0, 'Toyota')
(1, 'Audi')
(2, 'Mercedes-Benz')


eval()

This in-built eval() method in Python evaluates and executes a valid Python code.

eval("""print('Hello, World!')""")

Hello, World!

This method is powerful and dangerous as it allows for arbitrary code execution.


exec()

This in-built exec() method in Python executes a specified code object.

exec('x=8')
print(x)

8


filter()

This in-built filter() method in Python excludes items in an iterable.

numbers = [0x01, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def even(x):
    return x % 2 == 0

even = filter(even, numbers)
for e in even:
    print(e)

2
4
6
8
10


float()

This in-built float() method in Python will return a floating-point value of the numerical value passed.

print(float(10))

10.0


format()

This in-built format() method in Python will format a specified value.

print("Hello, {}!".format("John"))

Hello, John!


frozenset()

This in-built frozenset() method in Python will return a frozen set object.

my_fruits = ['kiwi', 'peach', 'grape']
my_fruits = frozenset(my_fruits)
print(my_fruits)
print(type(my_fruits))

frozenset({'kiwi', 'grape', 'peach'})
<class 'frozenset'>


getattr()

This in-built getattr() method returns the value of the specified attribute, which can be a method or a property.

class Person:
    name = "no_name"
    def __init__(self, name):
        self.name = name

print(getattr(Person, 'name'))

no_name


ADVERTISEMENT

globals()

This in-built globals() method in Python will return a dictionary containing all the global symbols.

print(globals())

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000262340B0F70>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\\Users\\x\\Desktop\\my\\test.py', '__cached__': None}


hasattr()

This in-built hasattr() method in Python will return True if the specified object has the specified method or property.

class Person:
    name = "no_name"
    def __init__(self, name):
        self.name = name

print(hasattr(Person, 'name'))

True


hash()

This in-built hash() method in Python will return the unique numeric representation of a specified object.

The output will probably be different from session from session.

print(hash(181.1))

230584300921356469


help()

This in-built help() method in Python will print out a message containing helpful information.

print(help())

Welcome to Python 3.9's help uti...(redacted to avoid plagiarism)


hex()

Python's in-built hex() method will take a base-2 or base-10 number and convert it into a hexadecimal value.

print(hex(10))
print(hex(0b1010))

0xa
0xa


id()

This in-built id() method in Python will return a unique numeric representation of an object. This id is globally unique.

The id generated will be different from session to session.

print(id([1, 2, 3,4]))

1900882392064


int()

This in-built int() method in Python will return an integer value.

print(int(1234.5678))

1234


isinstance()

This in-built isinstance() method in Python will return True if the specified object is an instance of an object.

print(isinstance([1, 2], list))

True


issubclass()

This in-built issubclass() method in Python will True if the specified class is a subclass.

class A:
    pass

class B(A):
   pass

print(issubclass(B, A))

True


iter()

This in-built iter() method in Python will return an iterable object.

i = iter([1, 2, 3, 4])
print(i)

<list_iterator object at 0x000001EF2FDF6FD0>


len()

This in-built len() method in Python will return the length of an object.

my_list = [1, 2, 3, 4]
my_list_len = len(my_list)
print(my_list_len)

4


list()

This in-built list() method in Python will return a List.

my_tuple = (1, 2, 3, 4)
my_list = list(my_tuple)
print(my_list)

[1, 2, 3, 4]


locals()

This in-built locals() method in Python will return the local symbols table.

print(locals())

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000016951290F70>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\Users\x\Desktop\my\test.py', '__cached__': None}


map()

This in-built map() method in Python will return the specified iterator.

def get_len(x):
    return len(x)

x = map(get_len, ('john', 'siri', 'maple'))
for i in x:
  print(i)

4
4
5


max()

This in-built max() method in Python will return the largest item in an iterable.

print(max((1, 2, 3, 45, 6)))

45


memoryview()

This in-built memoryview() method in Python will return a memory view object. A memory view object can be indexed.

m = memoryview(b"John Doe")
print(m[0])

74


min()

This in-built min() method in Python will return the smallest item in a list.

print(min([1, 2, 3, 4]))

1


next()

This in-built next() method in Python will return the next item in an iterable.

i = iter((1, 2, 3, 4))
print(next(i))
print(next(i))

1
2


object()

This in-built object() method in Python will return a new object.

print(object())

<object object at 0x000001E6184E8190>


oct()

This in-built oct() method in Python will format the number into octal representation. This method will return a string.

x = oct(8)
print(x, type(x))

0o10 <class 'str'>


open()

This in-built open() method in Python will attempt to establish a connection to a file. If successful, it will return a reference object; else, an exception will be raised.

f_handle = open("contacts.txt")
print(f_handle.readlines())
f_handle.close()


ord()

This in-built ord() method in Python will convert an integer representing the Unicode of the character.

print(ord('A'))

65


pow()

This in-built pow() method in Python will return the value of a to the power of b.

print(pow(2, 3))

8


print()

Python's in-built print() method will print the text to the standard output device, i.e., the screen terminal.

print("learnpython.tech")

learnpython.tech


property()

This in-built property() method in Python will gets, sets, and deletes a property.


range()

This in-built range() method in Python will return a sequence of a number.

for i in range(3):
    print(i)

0
1
2


repr()

This in-built repr() method in Python will return the readable representation of an object. This method will convert the object into its string representation.

x = repr([1, 2])
print(x, type(x))

[1, 2] <class 'str'>


reverse()

This in-built reverse() method in Python will reverse the iterator and return it.

numbers = [1, 2, 3]
numbers = reversed(numbers)
for n in numbers:
    print(n)

3
2
1


round()

This in-built round() method in Python will round a number and return it.

print(round(1.23))

1


set()

This in-built set() method in Python returns a new set object. This method accepts an iterable.

print(set((1, 2, 3, 4)))

{1, 2, 3, 4}


setattr()

This in-built method in Python will set an attribute(method or property) to an object.

# Adding a method
class Person:
    pass

def greet(cls):
    print("Hello!")

setattr(Person, 'greet', greet)
person = Person()
person.greet()

# Adding a property
class Person:
    pass

setattr(Person, 'name', 'James Bond')
person = Person()
print(person.name)

Hello!
James Bond


slice()

This in-built slice() method in Python returns a slice object.

s = slice(2)
x = (1, 2, 3)[s]
print(x)

(1, 2)


sorted()

This in-built sorted() method in Python accepts an iterable and returns a sorted list.

print(sorted([5, 6, 7, 2,3, 1, 0]))

[0, 1, 2, 3, 5, 6, 7]


str()

This in-built str() method in Python will convert the object into a string.

print(str(1234))
print(str({1:1}))

1234
{1: 1}


sum()

This in-built sum() method in Python will return the sum of all items in an iterator.

print(sum((1,  2, 3, 4)))

10


super()

This in-built super() method in Python returns the instance of the superclass. This method is discussed in classes.


tuple()

This in-built tuple() method in Python return accepts an iterable and returns a tuple object.

print(tuple([1, 2, 3, 4]))

(1, 2, 3, 4)


type()

This in-built type() method in Python returns the type of the object passed.

print(type(1))
print(type({1:1}))

<class 'int'>
<class 'dict'>


vars()

This in-built vars() method in Python returns the object's __dict__ property.

print(vars())

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000016C212C0F70>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\Users\x\Desktop\my\test.py', '__cached__': None}


zip()

This in-built zip() method in Python will return an iterator from more than one iterators.

i = zip((1, 2), [3, 4])
for n in i:
    print(n)

(1, 3)
(2, 4)


Conclusion

In this chapter, we learned about the importance of using the in-built methods in reducing the workload by using a standard set of methods to avoid potential errors or bugs. Additionally, we briefed upon all in-built methods.


ADVERTISEMENT



All product names, logos, and brands are property of their respective owners.