Python Built-in Functions with Examples

Last updated 1 month, 3 weeks ago | 123 views 75     5

Tags:- Python

Python provides a comprehensive set of built-in functions that you can use right out of the box. These functions simplify many common tasks and improve productivity. Below is a detailed guide to Python's built-in functions, categorized with at least one example for each.


Type Conversion Functions

int()

Converts a number or string to an integer.

print(int("10"))  # Output: 10

float()

Converts a number or string to a float.

print(float("3.14"))  # Output: 3.14

str()

Converts an object to a string.

print(str(100))  # Output: '100'

bool()

Converts a value to a boolean.

print(bool(""))  # Output: False

list()

Converts an iterable to a list.

print(list("abc"))  # Output: ['a', 'b', 'c']

tuple()

Converts an iterable to a tuple.

print(tuple([1, 2, 3]))  # Output: (1, 2, 3)

set()

Converts an iterable to a set.

print(set([1, 2, 2, 3]))  # Output: {1, 2, 3}

dict()

Creates a dictionary.

print(dict([("a", 1), ("b", 2)]))  # Output: {'a': 1, 'b': 2}

Mathematical Functions

abs()

Returns the absolute value.

print(abs(-5))  # Output: 5

round()

Rounds a number to nearest integer or specified decimal.

print(round(3.14159, 2))  # Output: 3.14

min()

Returns the smallest item.

print(min([3, 1, 2]))  # Output: 1

max()

Returns the largest item.

print(max([3, 1, 2]))  # Output: 3

pow()

Returns x to the power of y.

print(pow(2, 3))  # Output: 8

divmod()

Returns quotient and remainder.

print(divmod(7, 3))  # Output: (2, 1)

Sequence Functions

len()

Returns length of an object.

print(len("hello"))  # Output: 5

sum()

Returns sum of items.

print(sum([1, 2, 3]))  # Output: 6

sorted()

Returns sorted list.

print(sorted([3, 1, 2]))  # Output: [1, 2, 3]

reversed()

Returns reversed iterator.

print(list(reversed([1, 2, 3])))  # Output: [3, 2, 1]

enumerate()

Returns an enumerate object.

for i, v in enumerate(["a", "b"]):
    print(i, v)

zip()

Combines iterables.

print(list(zip([1, 2], ['a', 'b'])))  # Output: [(1, 'a'), (2, 'b')]

range()

Generates a sequence of numbers.

print(list(range(3)))  # Output: [0, 1, 2]

Object Handling Functions

type()

Returns the type of object.

print(type("hello"))  # Output: <class 'str'>

isinstance()

Checks if object is instance of class.

print(isinstance(10, int))  # Output: True

id()

Returns identity of object.

x = 100
print(id(x))  # Output: memory address

hasattr()

Checks if object has attribute.

class Test:
    a = 1
print(hasattr(Test, 'a'))  # Output: True

getattr()

Gets attribute value.

class Test:
    a = 1
print(getattr(Test, 'a'))  # Output: 1

setattr()

Sets attribute value.

class Test:
    pass
setattr(Test, 'a', 1)
print(Test.a)  # Output: 1

callable()

Checks if object is callable.

print(callable(len))  # Output: True

Input/Output Functions

print()

Prints output to console.

print("Hello, World!")

input()

Reads a line from input.

# name = input("Enter your name: ")
# print(f"Hello, {name}!")

(Note: Commented to avoid blocking execution)


Functional Programming

map()

Applies function to items.

print(list(map(str.upper, ['a', 'b'])))  # Output: ['A', 'B']

filter()

Filters items based on condition.

print(list(filter(lambda x: x > 0, [-1, 0, 1])))  # Output: [1]

any()

True if any item is true.

print(any([0, False, 1]))  # Output: True

all()

True if all items are true.

print(all([1, True, 'a']))  # Output: True

eval()

Evaluates string as Python expression.

print(eval("2 + 2"))  # Output: 4

exec()

Executes dynamically created Python code.

exec("x = 5")
print(x)  # Output: 5

Miscellaneous Functions

help()

Displays help info.

# help(len)  # Uncomment to view help

dir()

Lists attributes of an object.

print(dir(str))  # Output: [...list of string methods...]

bin()

Converts to binary.

print(bin(10))  # Output: '0b1010'

hex()

Converts to hexadecimal.

print(hex(255))  # Output: '0xff'

oct()

Converts to octal.

print(oct(8))  # Output: '0o10'

chr()

Returns character for Unicode code.

print(chr(65))  # Output: 'A'

ord()

Returns Unicode code for character.

print(ord('A'))  # Output: 65

Summary

Python's built-in functions make it easier to handle a wide variety of common programming tasks without extra libraries. Understanding and using them effectively can greatly improve your development speed and code quality.