Built-In Methods Flashcards
abs(x)
abs(x)
accepts an integer or a float
returns the absolute value of that number
all()
accepts an iterable
returns true if ALL elements in the iterable are True
any()
accepts an iterable
returns true if ANY element in the iterable is True
ascii()
accepts any object (strings, Tuples, lists)
returns a readable version of object and replaces any non-ascii chars with escaped chars
bool()
accepts an object
returns a boolean value after standard truth-testing procedure
This always returns true unless…
object is empty like: [] {} ()
object is False
object is zero
object is None
callable()
accepts an Object
returns True if X is callable
for example, built-in functions and classes are both callable
delattr()
delattr(object, str)
deletes a property from an object, does not return anything.
string must be one of the objects attributes
dict()
Accepts keyword arguments
Returns a new python dictionary
example:
dict(name = “John”, age = 36, country = “Norway”)
enumerate()
enumerate(iterable, start=0)
start = the index value from which the counter is to be started
returns an enumerate object with index/element pairsfromat
example:
seasons = [‘spring’, ‘summer’, ‘fall’, ‘winter’]
list(enumerate(seasons))
// [(0, ‘spring’), (1, ‘summer’), (2, ‘fall’), (3, ‘winter’)]
filter()
filter(truth-test function, iterable)
returns the elements in the iterable that return true in the filter function
use list() to view results
example:
seasons = [‘spring’, ‘summer’, ‘fall’, ‘winter’]
def filter_func(item):
return len(item) == 4
list(filter(filter_func, seasons)
// [‘fall’]
eval()
eval(string)
evaluates the specified expression
eval(“3+1”) = 4
exec()
exec(object)
executes the specified Python code
NOTE: eval() can only accept a single expression
Whereas exec() can accept large blocks of code
float()
accepts a number or a string
returns a floating-point number
getattr()
getattr(object, attribute, default)
returns object[attribute] if attribute is available
or default value if provided
otherwise, returns AttributeError
hasattr()
hasattr(object, attribute)
checks if object has the given named attribute
returns True / False