Built-in Functions
What You'll Learn: In this tutorial, you'll explore various built-in functions in Python that can help you perform common tasks quickly and easily.
Key Built-in Functions
abs()- Returns the absolute value of a number.Example:
pythonprint(abs(-5)) # Output: 5
all()- Returns True if all items in an iterable object are true.Example:
pythonprint(all([True, True, False])) # Output: False
any()- Returns True if any item in an iterable object is true.Example:
pythonprint(any([True, False, False])) # Output: True
ascii()- Returns a readable version of an object. Replaces non-ascii characters with escape characters.Example:
pythonprint(ascii("Café")) # Output: 'Caf\\xe9'
bin()- Returns the binary version of a number.Example:
pythonprint(bin(10)) # Output: '0b1010'
bool()- Returns the boolean value of the specified object.Example:
pythonprint(bool(0)) # Output: False
bytearray()- Returns an array of bytes.Example:
pythonprint(bytearray(5)) # Output: bytearray(b'\x00\x00\x00\x00\x00')
bytes()- Returns a bytes object.Example:
pythonprint(bytes(5)) # Output: b'\x00\x00\x00\x00\x00'
callable()- Returns True if the specified object is callable, otherwise False.Example:
pythonprint(callable(print)) # Output: True
chr()- Returns a character from the specified Unicode code.Example:
pythonprint(chr(97)) # Output: 'a'
classmethod()- Converts a method into a class method.Example:
pythonclass MyClass: @classmethod def my_class_method(cls): pass
compile()- Returns the specified source as an object, ready to be executed.Example:
pythoncode = "print('Hello, World!')" compiled_code = compile(code, 'example', 'exec') exec(compiled_code)
complex()- Returns a complex number.Example:
pythonprint(complex(1, 2)) # Output: (1+2j)
delattr()- Deletes the specified attribute (property or method) from the specified object.Example:
pythonclass MyClass: x = 5 delattr(MyClass, 'x')
dict()- Returns a dictionary (Array).Example:
pythonprint(dict(a=1, b=2)) # Output: {'a': 1, 'b': 2}
dir()- Returns a list of the specified object's properties and methods.Example:
pythonprint(dir(list)) # Output: List of list methods
divmod()- Returns the quotient and the remainder when argument1 is divided by argument2.Example:
pythonprint(divmod(10, 3)) # Output: (3, 1)
enumerate()- Takes a collection (e.g., a tuple) and returns it as an enumerate object.Example:
pythonmy_list = ['a', 'b', 'c'] for index, value in enumerate(my_list): print(index, value)
eval()- Evaluates and executes an expression.Example:
pythonx = 1 print(eval('x + 1')) # Output: 2
exec()- Executes the specified code (or object).Example:
pythoncode = "print('Hello, World!')" exec(code)
filter()- Use a filter function to exclude items in an iterable object.Example:
pythonmy_list = [1, 2, 3, 4, 5] filtered_list = list(filter(lambda x: x % 2 == 0, my_list)) print(filtered_list) # Output: [2, 4]
float()- Returns a floating point number.Example:
pythonprint(float(5)) # Output: 5.0
format()- Formats a specified value.Example:
pythonprint(format(1234, ",")) # Output: '1,234'
frozenset()- Returns a frozenset object.Example:
pythonmy_set = frozenset([1, 2, 3]) print(my_set) # Output: frozenset({1, 2, 3})
getattr()- Returns the value of the specified attribute (property or method).Example:
pythonclass MyClass: x = 5 print(getattr(MyClass, 'x')) # Output: 5
globals()- Returns the current global symbol table as a dictionary.Example:
pythonprint(globals()) # Output: Dictionary of global variables
hasattr()- Returns True if the specified object has the specified attribute (property/method).Example:
pythonclass MyClass: x = 5 print(hasattr(MyClass, 'x')) # Output: True
hash()- Returns the hash value of a specified object.Example:
pythonprint(hash("hello")) # Output: Hash value
help()- Executes the built-in help system.Example:
pythonhelp(print) # Output: Documentation for the print function
hex()- Converts a number into a hexadecimal value.Example:
pythonprint(hex(255)) # Output: '0xff'
id()- Returns the id of an object.Example:
pythonx = 5 print(id(x)) # Output: Object ID
input()- Allows user input.Example:
pythonname = input("Enter your name: ") print(name)
int()- Returns an integer number.Example:
pythonprint(int("10")) # Output: 10
isinstance()- Returns True if a specified object is an instance of a specified object.Example:
pythonprint(isinstance(5, int)) # Output: True
issubclass()- Returns True if a specified class is a subclass of a specified object.Example:
pythonclass A: pass class B(A): pass print(issubclass(B, A)) # Output: True
iter()- Returns an iterator object.Example:
pythonmy_list = [1, 2, 3] my_iter = iter(my_list) print(next(my_iter)) # Output: 1
len()- Returns the length of an object.Example:
pythonprint(len("hello")) # Output: 5
list()- Returns a list.Example:
pythonprint(list((1, 2, 3))) # Output: [1, 2, 3]
locals()- Returns an updated dictionary of the current local symbol table.Example:
pythondef my_function(): local_var = 10 print(locals()) # Output: Dictionary of local variables my_function()
map()- Returns the specified iterator with the specified function applied to each item.Example:
pythondef add_one(x): return x + 1 my_list = [1, 2, 3] result = map(add_one, my_list) print(list(result)) # Output: [2, 3, 4]
max()- Returns the largest item in an iterable.Example:
pythonprint(max([1, 2, 3, 4])) # Output: 4
memoryview()- Returns a memory view object.Example:
pythonmy_bytes = b"Hello" mv = memoryview(my_bytes) print(mv[1]) # Output: 101
min()- Returns the smallest item in an iterable.Example:
pythonprint(min([1, 2, 3, 4])) # Output: 1
next()- Returns the next item in an iterable.Example:
pythonmy_iter = iter([1, 2, 3]) print(next(my_iter)) # Output: 1
object()- Returns a new object.Example:
pythonobj = object() print(type(obj)) # Output: <class 'object'>
oct()- Converts a number into an octal.Example:
pythonprint(oct(8)) # Output: '0o10'
open()- Opens a file and returns a file object.Example:
pythonfile = open('example.txt', 'r') content = file.read() file.close()
ord()- Convert an integer representing the Unicode of the specified character.Example:
pythonprint(ord('a')) # Output: 97
pow()- Returns the value of x to the power of y.Example:
pythonprint(pow(2, 3)) # Output: 8
print()- Prints to the standard output device.Example:
pythonprint("Hello, World!") # Output: Hello, World!
property()- Gets, sets, deletes a property.Example:
pythonclass MyClass: def __init__(self): self._x = None def get_x(self): return self._x def set_x(self, value): self._x = value def del_x(self): del self._x x = property(get_x, set_x, del_x) obj = MyClass() obj.x = 10 print(obj.x) # Output: 10
range()- Returns a sequence of numbers, starting from 0 and increments by 1 (by default).Example:
pythonprint(list(range(5))) # Output: [0, 1, 2, 3, 4]
repr()- Returns a readable version of an object.Example:
pythonprint(repr("Hello, World!")) # Output: 'Hello, World!'
reversed()- Returns a reversed iterator.Example:
pythonprint(list(reversed([1, 2, 3]))) # Output: [3, 2, 1]
round()- Rounds a number.Example:
pythonprint(round(5.678, 2)) # Output: 5.68
set()- Returns a new set object.Example:
pythonmy_set = set([1, 2, 3]) print(my_set) # Output: {1, 2, 3}
setattr()- Sets an attribute (property/method) of an object.Example:
pythonclass MyClass: x = 5 setattr(MyClass, 'x', 10) print(MyClass.x) # Output: 10
slice()- Returns a slice object.Example:
pythonmy_slice = slice(1, 4) print([1, 2, 3, 4, 5][my_slice]) # Output: [2, 3, 4]
sorted()- Returns a sorted list.Example:
pythonprint(sorted([3, 1, 4, 1, 5])) # Output: [1, 1, 3, 4, 5]
staticmethod()- Converts a method into a static method.Example:
pythonclass MyClass: @staticmethod def my_static_method(): print("Static method called") MyClass.my_static_method()
str()- Returns a string object.Example:
pythonprint(str(123)) # Output: '123'
sum()- Sums the items of an iterator.Example:
pythonprint(sum([1, 2, 3])) # Output: 6
super()- Returns an object that represents the parent class.Example:
pythonclass A: def __init__(self): print("A's init called") class B(A): def __init__(self): super().__init__() print("B's init called") obj = B()
tuple()- Returns a tuple.Example:
pythonprint(tuple([1, 2, 3])) # Output: (1, 2, 3)
type()- Returns the type of an object.Example:
pythonprint(type(123)) # Output: <class 'int'>
vars()- Returns the__dict__property of an object.Example:
pythonclass MyClass: x = 5 obj = MyClass() print(vars(obj)) # Output: {}
zip()- Returns an iterator, from two or more iterators.Example:
pythonlist1 = [1, 2, 3] list2 = ['a', 'b', 'c'] print(list(zip(list1, list2))) # Output: [(1, 'a'), (2, 'b'), (3, 'c')]
Try It Yourself: Fun Exercises
- Explore Number Functions:
- Use
abs(),bin(), andpow()to experiment with different numbers and see how they work.
- Use
- Work with Booleans:
- Use
all()andany()to test different lists of boolean values.
- Use
- Character and Byte Manipulations:
- Use
chr()andbytes()to understand how characters and byte objects are handled in Python.
- Use
Summary:
In this Python tutorial, we explored various built-in functions that are essential for performing common tasks. These functions make it easier to write efficient and effective code. Keep experimenting and have fun with Python!