Builtins

There are lot of builtin functions (no need to import them) that are always available.

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

Some example that we already saw:

  • print()

  • len()

  • pow()

  • int()

  • str()

  • type()

  • isinstance()

  • range()

  • sum(), max(), min(), enumerate(), round()...

But there are much more of them!

Built-in Functions

abs()

dict()

help()

min()

setattr()

all()

dir()

hex()

next()

slice()

any()

divmod()

id()

object()

sorted()

ascii()

enumerate()

input()

oct()

staticmethod()

bin()

eval()

int()

open()

str()

bool()

exec()

isinstance()

ord()

sum()

bytearray()

filter()

issubclass()

pow()

super()

bytes()

float()

iter()

print()

tuple()

callable()

format()

len()

property()

type()

chr()

frozenset()

list()

range()

vars()

classmethod()

getattr()

locals()

repr()

zip()

compile()

globals()

map()

reversed()

__import__()

complex()

hasattr()

max()

round()

delattr()

hash()

memoryview()

set()

Most important builtins

  • Types are callable:

    • int()

    • float()

    • str()

    • list()

    • dict()

    • set()

    • bool()

    • frozenset()

    • bytes()

    • bytearray()

  • Introspection:

    • id()

    • dir()

    • type()

    • isinstance()

    • issubclass()

    • callable()

    • hash()

    • help()

  • __import__()

  • len(), print()

  • abs(), sum(), max(), min(), pow(), round()

  • range(), sorted(), reversed(), enumerate(), all(), any()

  • open()

  • globals(), locals(), (not builtins but don't forget about: global, nonlocal)

Access to object attributes

  • getattr(obj, "attr_name"[, default])

  • hasattr(obj, "attr_name")

  • setattr(obj, "attr_name", value)

  • delattr(obj, "attr_name")

🪄 Code:

class A(object):
    a = 5
    
a_object = A()
print( hasattr(a_object, "a") )
print( getattr(a_object, "a") )
setattr(a_object, "b", "Wow! Adding attrs like haxxxors")
print( a_object.b )

📟 Output:

True
5
Wow! Adding attrs like haxxxors

🪄 Code:

getattr("Hello World", "lower")()

📟 Output:

'hello world'

# Iterable and Iterator

Iterable is the source of data for iterator, usually - some sequence.

[1, 2, 3]
("a", "b")
"Hello!"
{1: 2, "a": 3}
{1, 2, 3}
range(10)
reversed("abc")

Iterator - an abstract object that is capable of yielding "next" item and raising StopIteration in the end.

iter("abce")

next(iter("abce"))
iter("abce").__next__()

for i in "abcd":
    print(i)

Last updated