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

  1. abs() - Returns the absolute value of a number.
    • Example:

      python
      print(abs(-5))  # Output: 5
      
  2. all() - Returns True if all items in an iterable object are true.
    • Example:

      python
      print(all([True, True, False]))  # Output: False
      
  3. any() - Returns True if any item in an iterable object is true.
    • Example:

      python
      print(any([True, False, False]))  # Output: True
      
  4. ascii() - Returns a readable version of an object. Replaces non-ascii characters with escape characters.
    • Example:

      python
      print(ascii("Café"))  # Output: 'Caf\\xe9'
      
  5. bin() - Returns the binary version of a number.
    • Example:

      python
      print(bin(10))  # Output: '0b1010'
      
  6. bool() - Returns the boolean value of the specified object.
    • Example:

      python
      print(bool(0))  # Output: False
      
  7. bytearray() - Returns an array of bytes.
    • Example:

      python
      print(bytearray(5))  # Output: bytearray(b'\x00\x00\x00\x00\x00')
      
  8. bytes() - Returns a bytes object.
    • Example:

      python
      print(bytes(5))  # Output: b'\x00\x00\x00\x00\x00'
      
  9. callable() - Returns True if the specified object is callable, otherwise False.
    • Example:

      python
      print(callable(print))  # Output: True
      
  10. chr() - Returns a character from the specified Unicode code.
    • Example:

      python
      print(chr(97))  # Output: 'a'
      
  11. classmethod() - Converts a method into a class method.
    • Example:

      python
      class MyClass:
          @classmethod
          def my_class_method(cls):
              pass
      
  12. compile() - Returns the specified source as an object, ready to be executed.
    • Example:

      python
      code = "print('Hello, World!')"
      compiled_code = compile(code, 'example', 'exec')
      exec(compiled_code)
      
  13. complex() - Returns a complex number.
    • Example:

      python
      print(complex(1, 2))  # Output: (1+2j)
      
  14. delattr() - Deletes the specified attribute (property or method) from the specified object.
    • Example:

      python
      class MyClass:
          x = 5
      
      delattr(MyClass, 'x')
      
  15. dict() - Returns a dictionary (Array).
    • Example:

      python
      print(dict(a=1, b=2))  # Output: {'a': 1, 'b': 2}
      
  16. dir() - Returns a list of the specified object's properties and methods.
    • Example:

      python
      print(dir(list))  # Output: List of list methods
      
  17. divmod() - Returns the quotient and the remainder when argument1 is divided by argument2.
    • Example:

      python
      print(divmod(10, 3))  # Output: (3, 1)
      
  18. enumerate() - Takes a collection (e.g., a tuple) and returns it as an enumerate object.
    • Example:

      python
      my_list = ['a', 'b', 'c']
      for index, value in enumerate(my_list):
          print(index, value)
      
  19. eval() - Evaluates and executes an expression.
    • Example:

      python
      x = 1
      print(eval('x + 1'))  # Output: 2
      
  20. exec() - Executes the specified code (or object).
    • Example:

      python
      code = "print('Hello, World!')"
      exec(code)
      
  21. filter() - Use a filter function to exclude items in an iterable object.
    • Example:

      python
      my_list = [1, 2, 3, 4, 5]
      filtered_list = list(filter(lambda x: x % 2 == 0, my_list))
      print(filtered_list)  # Output: [2, 4]
      
  22. float() - Returns a floating point number.
    • Example:

      python
      print(float(5))  # Output: 5.0
      
  23. format() - Formats a specified value.
    • Example:

      python
      print(format(1234, ","))  # Output: '1,234'
      
  24. frozenset() - Returns a frozenset object.
    • Example:

      python
      my_set = frozenset([1, 2, 3])
      print(my_set)  # Output: frozenset({1, 2, 3})
      
  25. getattr() - Returns the value of the specified attribute (property or method).
    • Example:

      python
      class MyClass:
          x = 5
      
      print(getattr(MyClass, 'x'))  # Output: 5
      
  26. globals() - Returns the current global symbol table as a dictionary.
    • Example:

      python
      print(globals())  # Output: Dictionary of global variables
      
  27. hasattr() - Returns True if the specified object has the specified attribute (property/method).
    • Example:

      python
      class MyClass:
          x = 5
      
      print(hasattr(MyClass, 'x'))  # Output: True
      
  28. hash() - Returns the hash value of a specified object.
    • Example:

      python
      print(hash("hello"))  # Output: Hash value
      
  29. help() - Executes the built-in help system.
    • Example:

      python
      help(print)  # Output: Documentation for the print function
      
  30. hex() - Converts a number into a hexadecimal value.
    • Example:

      python
      print(hex(255))  # Output: '0xff'
      
  31. id() - Returns the id of an object.
    • Example:

      python
      x = 5
      print(id(x))  # Output: Object ID
      
  32. input() - Allows user input.
    • Example:

      python
      name = input("Enter your name: ")
      print(name)
      
  33. int() - Returns an integer number.
    • Example:

      python
      print(int("10"))  # Output: 10
      
  34. isinstance() - Returns True if a specified object is an instance of a specified object.
    • Example:

      python
      print(isinstance(5, int))  # Output: True
      
  35. issubclass() - Returns True if a specified class is a subclass of a specified object.
    • Example:

      python
      class A:
          pass
      
      class B(A):
          pass
      
      print(issubclass(B, A))  # Output: True
      
  36. iter() - Returns an iterator object.
    • Example:

      python
      my_list = [1, 2, 3]
      my_iter = iter(my_list)
      print(next(my_iter))  # Output: 1
      
  37. len() - Returns the length of an object.
    • Example:

      python
      print(len("hello"))  # Output: 5
      
  38. list() - Returns a list.
    • Example:

      python
      print(list((1, 2, 3)))  # Output: [1, 2, 3]
  39. locals() - Returns an updated dictionary of the current local symbol table.
    • Example:

      python
      def my_function():
          local_var = 10
          print(locals())  # Output: Dictionary of local variables
      
      my_function()
      
  40. map() - Returns the specified iterator with the specified function applied to each item.
    • Example:

      python
      def add_one(x):
          return x + 1
      
      my_list = [1, 2, 3]
      result = map(add_one, my_list)
      print(list(result))  # Output: [2, 3, 4]
      
  41. max() - Returns the largest item in an iterable.
    • Example:

      python
      print(max([1, 2, 3, 4]))  # Output: 4
      
  42. memoryview() - Returns a memory view object.
    • Example:

      python
      my_bytes = b"Hello"
      mv = memoryview(my_bytes)
      print(mv[1])  # Output: 101
      
  43. min() - Returns the smallest item in an iterable.
    • Example:

      python
      print(min([1, 2, 3, 4]))  # Output: 1
      
  44. next() - Returns the next item in an iterable.
    • Example:

      python
      my_iter = iter([1, 2, 3])
      print(next(my_iter))  # Output: 1
      
  45. object() - Returns a new object.
    • Example:

      python
      obj = object()
      print(type(obj))  # Output: <class 'object'>
      
  46. oct() - Converts a number into an octal.
    • Example:

      python
      print(oct(8))  # Output: '0o10'
      
  47. open() - Opens a file and returns a file object.
    • Example:

      python
      file = open('example.txt', 'r')
      content = file.read()
      file.close()
      
  48. ord() - Convert an integer representing the Unicode of the specified character.
    • Example:

      python
      print(ord('a'))  # Output: 97
      
  49. pow() - Returns the value of x to the power of y.
    • Example:

      python
      print(pow(2, 3))  # Output: 8
      
  50. print() - Prints to the standard output device.
    • Example:

      python
      print("Hello, World!")  # Output: Hello, World!
      
  51. property() - Gets, sets, deletes a property.
    • Example:

      python
      class 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
      
  52. range() - Returns a sequence of numbers, starting from 0 and increments by 1 (by default).
    • Example:

      python
      print(list(range(5)))  # Output: [0, 1, 2, 3, 4]
      
  53. repr() - Returns a readable version of an object.
    • Example:

      python
      print(repr("Hello, World!"))  # Output: 'Hello, World!'
      
  54. reversed() - Returns a reversed iterator.
    • Example:

      python
      print(list(reversed([1, 2, 3])))  # Output: [3, 2, 1]
      
  55. round() - Rounds a number.
    • Example:

      python
      print(round(5.678, 2))  # Output: 5.68
      
  56. set() - Returns a new set object.
    • Example:

      python
      my_set = set([1, 2, 3])
      print(my_set)  # Output: {1, 2, 3}
      
  57. setattr() - Sets an attribute (property/method) of an object.
    • Example:

      python
      class MyClass:
          x = 5
      
      setattr(MyClass, 'x', 10)
      print(MyClass.x)  # Output: 10
      
  58. slice() - Returns a slice object.
    • Example:

      python
      my_slice = slice(1, 4)
      print([1, 2, 3, 4, 5][my_slice])  # Output: [2, 3, 4]
      
  59. sorted() - Returns a sorted list.
    • Example:

      python
      print(sorted([3, 1, 4, 1, 5]))  # Output: [1, 1, 3, 4, 5]
      
  60. staticmethod() - Converts a method into a static method.
    • Example:

      python
      class MyClass:
          @staticmethod
          def my_static_method():
              print("Static method called")
      
      MyClass.my_static_method()
      
  61. str() - Returns a string object.
    • Example:

      python
      print(str(123))  # Output: '123'
      
  62. sum() - Sums the items of an iterator.
    • Example:

      python
      print(sum([1, 2, 3]))  # Output: 6
      
  63. super() - Returns an object that represents the parent class.
    • Example:

      python
      class A:
          def __init__(self):
              print("A's init called")
      
      class B(A):
          def __init__(self):
              super().__init__()
              print("B's init called")
      
      obj = B()
      
  64. tuple() - Returns a tuple.
    • Example:

      python
      print(tuple([1, 2, 3]))  # Output: (1, 2, 3)
      
  65. type() - Returns the type of an object.
    • Example:

      python
      print(type(123))  # Output: <class 'int'>
      
  66. vars() - Returns the __dict__ property of an object.
    • Example:

      python
      class MyClass:
          x = 5
      
      obj = MyClass()
      print(vars(obj))  # Output: {}
      
  67. zip() - Returns an iterator, from two or more iterators.
    • Example:

      python
      list1 = [1, 2, 3]
      list2 = ['a', 'b', 'c']
      print(list(zip(list1, list2)))  # Output: [(1, 'a'), (2, 'b'), (3, 'c')]
      

Try It Yourself: Fun Exercises

  1. Explore Number Functions:
    • Use abs(), bin(), and pow() to experiment with different numbers and see how they work.
  2. Work with Booleans:
    • Use all() and any() to test different lists of boolean values.
  3. Character and Byte Manipulations:
    • Use chr() and bytes() to understand how characters and byte objects are handled in Python.

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!