0% found this document useful (0 votes)
6 views3 pages

Python Built-in Functions Overview

The document provides examples of Python built-in functions, covering type conversion, mathematical functions, sequence and collection handling, input/output, object and type information, functional programming, and exception handling. It includes code snippets demonstrating each category, such as converting types, performing calculations, manipulating lists, and handling errors. Additionally, it showcases how to access built-in functions and use functional programming techniques like map and filter.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views3 pages

Python Built-in Functions Overview

The document provides examples of Python built-in functions, covering type conversion, mathematical functions, sequence and collection handling, input/output, object and type information, functional programming, and exception handling. It includes code snippets demonstrating each category, such as converting types, performing calculations, manipulating lists, and handling errors. Additionally, it showcases how to access built-in functions and use functional programming techniques like map and filter.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Built-in Functions: Program Examples

Type Conversion
a = "10"
print(int(a))
print(float(a))
print(str(5.5))
print(bool(0))
print(list("abc"))

Mathematical Functions
print(abs(-7))
print(round(4.567, 2))
print(pow(2, 3))
print(divmod(9, 2))
print(min(5, 2, 9))
print(max(5, 2, 9))
print(sum([1, 2, 3, 4]))

Sequence & Collection Handling


lst = [5, 8, 1, 7]
print(len(lst))
print(sorted(lst))
print(list(reversed(lst)))

for i, val in enumerate(lst):


print(i, val)

a = [1, 2]
b = [3, 4]
print(list(zip(a, b)))
print(list(range(5)))
print(any([False, True]))
print(all([True, True]))

Input/Output
name = input("Enter your name: ")
print("Hello", name)

Object & Type Information


x = 10
print(type(x))
print(isinstance(x, int))
print(id(x))
print(dir(x))

class Test:
val = 5

obj = Test()
print(hasattr(obj, 'val'))
setattr(obj, 'newval', 10)
print(getattr(obj, 'newval'))
delattr(obj, 'newval')

Functional Programming
nums = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, nums))
print(squared)

even = list(filter(lambda x: x % 2 == 0, nums))


print(even)

a = [1, 2]
b = ['a', 'b']
print(list(zip(a, b)))

Miscellaneous
help(print)
print(eval("5+10"))
code = "print('Hello World!')"
exec(code)
print(globals())

Exception Handling
x=5
assert x == 5

try:
raise ValueError("Custom error")
except ValueError as e:
print(e)

List all built-in functions


print(dir(__builtins__))

Common questions

Powered by AI

The 'sorted' function returns a new list that is a sorted version of the provided iterable, leaving the original unchanged. In contrast, 'list.sort()' sorts the list in place and returns None. 'sorted' is used when a non-destructive sort is desired, while 'list.sort()' is preferred for efficiency when the original list can be altered as it avoids creating an extra list, thus reducing memory use .

The 'zip' function pairs elements from each given sequence together into tuples; if the input lists are of unequal lengths, 'zip' truncates to the shortest list's length so that no IndexError occurs. For example, using 'zip' with a = [1, 2] and b = ['a', 'b', 'c'] results in [(1, 'a'), (2, 'b')].

The 'abs' function returns the absolute value of a number, removing any negative sign, useful for magnitude calculations. In contrast, 'round' adjusts a floating-point number to the nearest integer or specified decimal places, aiding in numerical approximations and ensuring precision in calculations .

The 'eval' function executes the provided string as a Python expression, which can lead to significant security risks if the input is not sanitized, as it might execute arbitrary code. Mitigation strategies include using 'ast.literal_eval' for safely evaluating strings containing Python literal expressions and validating inputs thoroughly before evaluation .

'Divmod' provides simultaneous quotient and remainder from division, reducing redundancy and enhancing efficiency when both values are needed. Separate division and modulo calls require two operations, making 'divmod' more efficient in terms of performance when both division results are sought, especially in loops .

Functions like 'map' apply a given function to all items in an iterable and return a map object, whereas 'filter' applies a function to test each item and include it if the function returns True. These can improve code readability by providing concise and expressive means for data transformation, benefiting efficiency by utilizing iterators for processing data without constructing intermediate lists unnecessarily .

The 'hasattr' function checks if an object has an attribute with the specified name, returning either True or False, which helps in determining object properties dynamically. Its usage allows programmers to handle attributes flexibly, adding to dynamic behavior in object manipulation .

'Try' and 'except' blocks capture and handle exceptions, preventing programs from crashing due to unhandled errors. Effective practices include: catching specific exceptions to prevent broadly capturing errors, maintaining clear and concise 'try' blocks, and utilizing 'finally' for cleanup operations. This ensures robust error handling and maintains application stability .

'Enumerate' simplifies loop constructs by automatically providing both index and value without manually tracking indices. This leads to improved code readability and maintainability, especially in large loops. While there is negligible performance overhead compared to using a separate counter for indexing, the primary advantage is increased code clarity and reduced potential for off-by-one errors .

'Print' outputs data formatted as strings into the console, but it does not modify or evaluate expressions; it simply displays them. 'Eval', however, processes an input string as a Python expression and evaluates it, potentially altering the execution flow based on the results, with implications for operation security and results .

You might also like