Python Built-in Functions
Python has a rich set of built-in functions that perform various tasks such as mathematical operations, data manipulation, type conversions, input/output, and more. These functions are always available in the Python environment, meaning you don’t need to import any libraries to use them.
Here’s an overview of commonly used Python built-in functions, grouped by category:
1. Mathematical Functions
abs(x): Returns the absolute value of a number.abs(-5) # Output: 5pow(x, y): Returnsxraised to the powery.pow(2, 3) # Output: 8round(x, n): Rounds a numberxtondecimal places.round(3.14159, 2) # Output: 3.14min(*args)/max(*args): Returns the smallest or largest value from a set of values.min(1, 2, 3) # Output: 1 max(1, 2, 3) # Output: 3sum(iterable): Returns the sum of all items in an iterable.sum([1, 2, 3]) # Output: 6
2. Type Conversion Functions
int(x): Convertsxto an integer.int("10") # Output: 10float(x): Convertsxto a float.float("10.5") # Output: 10.5str(x): Convertsxto a string.str(10) # Output: "10"list(iterable): Converts an iterable to a list.list("abc") # Output: ['a', 'b', 'c']tuple(iterable): Converts an iterable to a tuple.tuple([1, 2, 3]) # Output: (1, 2, 3)dict(): Creates a dictionary.dict(a=1, b=2) # Output: {'a': 1, 'b': 2}set(iterable): Converts an iterable to a set (removing duplicates).set([1, 2, 2, 3]) # Output: {1, 2, 3}bool(x): Convertsxto a boolean (TrueorFalse).bool(1) # Output: True bool(0) # Output: False
3. Iterables and Iterator Functions
len(s): Returns the length of an object (string, list, etc.).len("hello") # Output: 5range(start, stop, step): Returns a sequence of numbers fromstarttostop(exclusive).list(range(1, 5)) # Output: [1, 2, 3, 4]map(function, iterable): Applies a function to each item in the iterable and returns a map object.list(map(str, [1, 2, 3])) # Output: ['1', '2', '3']filter(function, iterable): Filters items from an iterable based on a condition in the function.list(filter(lambda x: x > 2, [1, 2, 3])) # Output: [3]zip(*iterables): Combines elements from multiple iterables into tuples.list(zip([1, 2, 3], ['a', 'b', 'c'])) # Output: [(1, 'a'), (2, 'b'), (3, 'c')]enumerate(iterable): Returns an iterator that produces tuples of an index and an element from the iterable.list(enumerate(['a', 'b', 'c'])) # Output: [(0, 'a'), (1, 'b'), (2, 'c')]
4. Input/Output Functions
print(*objects): Prints the specified objects to the console.print("Hello, world!") # Output: Hello, world!input(prompt): Takes input from the user as a string.name = input("Enter your name: ")open(file, mode): Opens a file and returns a file object.file = open("example.txt", "r")
5. Object and Type-Related Functions
type(x): Returns the type of an object.type(10) # Output: <class 'int'>isinstance(obj, class): Checks if an object is an instance of a class.isinstance(10, int) # Output: Trueid(x): Returns the unique identifier of an object.id(10) # Output: unique memory addressdir([object]): Returns a list of attributes and methods of an object.dir([]) # Output: List of list attributes and methodshasattr(object, name): Checks if an object has a specified attribute.hasattr(obj, 'attribute_name')setattr(object, name, value): Sets an attribute of an object to a specific value.setattr(obj, 'attribute_name', value)getattr(object, name): Returns the value of a specified attribute of an object.getattr(obj, 'attribute_name')delattr(object, name): Deletes an attribute from an object.delattr(obj, 'attribute_name')
6. Advanced Functions
eval(expression): Evaluates a string expression as Python code.eval('2 + 2') # Output: 4exec(object): Executes a string or object as Python code.exec('print("Hello, world!")')callable(object): ReturnsTrueif the object appears to be callable (e.g., functions or classes).callable(print) # Output: True
7. Others
help([object]): Provides help documentation for an object.help(print)sorted(iterable, key=None, reverse=False): Returns a sorted list of the specified iterable.sorted([3, 1, 2]) # Output: [1, 2, 3]reversed(sequence): Returns a reverse iterator of the given sequence.list(reversed([1, 2, 3])) # Output: [3, 2, 1]any(iterable): ReturnsTrueif at least one element of the iterable is true.any([0, 1, 0]) # Output: Trueall(iterable): ReturnsTrueif all elements of the iterable are true.all([1, 2, 3]) # Output: True
Summary:
- Python provides a wide array of built-in functions that help in performing various common tasks.
- Functions such as
print(),len(),sum(),map(), andfilter()are useful in everyday programming. - Type conversion functions like
int(),str(),list(), andset()are useful for converting between types. - Functions like
eval(),exec(),help(), anddir()provide powerful tools for introspection and dynamic code execution.