0% found this document useful (0 votes)
56 views4 pages

Python Built-in Functions Overview

The document provides a comprehensive overview of Python's built-in functions along with examples for each function. It covers various data types and operations, such as converting types, manipulating collections, and performing mathematical computations. Each function is illustrated with a code snippet demonstrating its usage and expected output.

Uploaded by

avaneesh6808
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)
56 views4 pages

Python Built-in Functions Overview

The document provides a comprehensive overview of Python's built-in functions along with examples for each function. It covers various data types and operations, such as converting types, manipulating collections, and performing mathematical computations. Each function is illustrated with a code snippet demonstrating its usage and expected output.

Uploaded by

avaneesh6808
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 with Examples

int()
int("10") # => 10
float()
float("3.14") # => 3.14
complex()
complex(2, 3) # => (2+3j)
bool()
bool(0) # => False
str()
str(123) # => "123"
list()
list("abc") # => ['a', 'b', 'c']
tuple()
tuple([1, 2]) # => (1, 2)
set()
set([1, 2, 2]) # => {1, 2}
frozenset()
frozenset([1, 2]) # => frozenset({1, 2})
dict()
dict([('a', 1), ('b', 2)]) # => {'a': 1, 'b': 2}
bytes()
bytes("abc", "utf-8") # => b'abc'
bytearray()
bytearray("abc", "utf-8") # => bytearray(b'abc')
memoryview()
memoryview(b"abc")[0] # => 97
len()
len("hello") # => 5
range()
list(range(3)) # => [0, 1, 2]
enumerate()
list(enumerate(['a', 'b'])) # => [(0, 'a'), (1, 'b')]
zip()
list(zip([1, 2], ['a', 'b'])) # => [(1, 'a'), (2, 'b')]
map()
list(map([Link], ["a", "b"])) # => ['A', 'B']
filter()
list(filter(lambda x: x > 1, [1, 2, 3])) # => [2, 3]
reversed()
list(reversed([1, 2, 3])) # => [3, 2, 1]
sorted()
sorted([3, 1, 2]) # => [1, 2, 3]
all()
all([True, True]) # => True
any()
any([False, True]) # => True
abs()
abs(-5) # => 5
round()
round(3.1415, 2) # => 3.14
pow()
pow(2, 3) # => 8
divmod()
divmod(10, 3) # => (3, 1)
sum()
sum([1, 2, 3]) # => 6
max()
max([1, 5, 3]) # => 5
min()
min([1, 5, 3]) # => 1
type()
type(123) # => <class 'int'>
id()
id("hello") # => memory address
isinstance()
isinstance(123, int) # => True
issubclass()
issubclass(bool, int) # => True
callable()
callable(print) # => True
dir()
dir([]) # => list of list methods
vars()
class X: pass
vars(X()) # => {}
help()
help(str) # => opens help doc for str
globals()
globals()["x"] = 10 # => {"x": 10, ...}
locals()
def test(): a = 5; return locals() # => {"a": 5}
eval()
eval("2+2") # => 4
exec()
exec("x = 5") # => x is created
compile()
code = compile("print('hi')", "", "exec"); exec(code) # => hi
print()
print("Hello") # => Hello
open()
open("[Link]", "w") # => opens file for writing
getattr()
class X: a = 1
getattr(X, "a") # => 1
setattr()
class X: pass
setattr(X, "a", 100)
hasattr()
class X: a = 1
hasattr(X, "a") # => True
delattr()
class X: a = 1
delattr(X, "a")
property()
class X:
def get(self): return 5
a = property(get)
staticmethod()
class X:
@staticmethod
def f(): return 1
classmethod()
class X:
@classmethod
def f(cls): return cls
super()
class A: def greet(self): return "Hi"
class B(A): def greet(self): return super().greet()
object()
obj = object()
format()
format(255, "x") # => "ff"
hash()
hash("abc")
bin()
bin(5) # => "0b101"
oct()
oct(8) # => "0o10"
hex()
hex(255) # => "0xff"
ascii()
ascii("é") # => "'\xe9'"
ord()
ord("A") # => 65
chr()
chr(65) # => "A"
repr()
repr("hello") # => "'hello'"
__import__()
__import__("math").sqrt(9) # => 3.0

Common questions

Powered by AI

Using the 'property' decorator in Python permits attributes of classes to have getter, setter, and deleter functionality. This enhances the class's encapsulation by allowing controlled access and updates to attribute values indirectly, promoting a clean interface between the class's implementation and its clients. For example, defining a class attribute with a getter method using @property allows attribute access as if it were a simple attribute, while still maintaining logic that may compute or validate values dynamically, supporting encapsulation principles .

'Memoryview' provides a way to access the memory of an existing object without making a full copy, which is particularly advantageous when handling large binary data sequences as it reduces memory overhead. This is preferred in memory-critical applications because it enables efficient manipulation of a subset of data objects without additional memory allocation. For instance, memoryview(b'abc')[0] accesses part of a byte sequence directly, which can be crucial in optimizing performance when processing large files or data streams where full copies can be expensive .

The 'eval' function in Python executes the expression passed to it dynamically as a string, allowing computation of expressions that are generated at runtime. While it is powerful for executing dynamically constructed expressions, 'eval' poses significant security risks as it can execute arbitrary code. If user input is evaluated without proper validation, it can lead to code injection attacks. Developers must sanitize inputs and consider alternative approaches like 'ast.literal_eval' for safer evaluations of expressions where arbitrary code execution is not necessary .

The 'map' function applies a given function to all items of an input iterable, outputting a map object or iterator. It enhances data processing by applying transformations across collections in a concise manner. The 'map' function is advantageous over traditional loops when the transformation can be described with a single function call, allowing clearer, more readable code. For example, converting a list of lowercase strings ['a', 'b'] to uppercase can be succinctly done using list(map(str.upper, ['a', 'b'])), resulting in ['A', 'B'], eliminating the need for explicit loops .

The 'enumerate' function adds a counter to an iterable, returning it as an enumerate object. This is beneficial when an index is needed alongside the items for processing, providing clearer and more manageable code than traditional index-based loops. By unpacking the returned tuples directly onto the index and value, developers can avoid manual index management. For example, using enumerate(['a', 'b']) results in [(0, 'a'), (1, 'b')], making the process intuitive and concise, improving readability compared to handling separate lists or manually managing index variables in loops .

'Callable' checks if an object appears callable (i.e., if it can be called like a function). This is crucial in scenarios where the code dynamically interacts with functions or objects that may or may not be callable due to type conditions. For instance, determining if objects retrieved from a data structure can be executed as functions helps in creating dynamic execution flows without prior assumption of the callable nature, supporting polymorphism and extensible designs in applications which can dynamically invoke operations stored in containers .

The 'zip' function in Python takes iterables (like lists or tuples) as arguments and returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument iterables. It's useful in data processing for pairing related fields. For example, given two lists, names = ['Alice', 'Bob'] and scores = [85, 95], the 'zip' function can combine them into a list of tuples: list(zip(names, scores)) results in [('Alice', 85), ('Bob', 95)], efficiently aligning names with their corresponding scores .

A developer might choose 'frozenset' over a regular 'set' when the requirement is to maintain a collection of unique elements that should not be changed after creation. 'Frozenset' is immutable, offering advantages in data integrity by ensuring that the collection remains unchanged, which is important in scenarios where the dataset must remain constant or is used as a dictionary key. In terms of performance, frozensets may have faster lookup times compared to sets due to their immutability, which can optimize operations in large-scale data applications .

The 'filter' function in Python takes two arguments, a function and an iterable, and filters elements from the iterable for which the function returns True. It is preferred over list comprehensions when the filtering logic is complex or involves multiple conditions, due to its readability and ability to handle longer filtering functions passed as arguments. For example, filtering out numbers greater than 1 from a list [1, 2, 3] with 'filter' results in list(filter(lambda x: x > 1, [1, 2, 3])) which gives [2, 3].

The 'super' function in Python returns a temporary object of the superclass, allowing you to call its methods. This is particularly useful in method overriding within inheritance hierarchies, as it enables the derived class to extend or modify the behavior of the base class's methods without completely replacing them. For example, within a subclass B inheriting from class A, overriding the 'greet' method can incorporate additional logic but still call the superclass method: class B(A): def greet(self): return super().greet() + ", how are you?". This ensures that the original functionality is retained while enhancements are made .

You might also like