Python interpreter has number of built-in functions which are listed below.
abs(x)
abs(x) returns absolute value of a number. The argument can be an integer or floating point number.
if argument is complex number its magnitude is returned.
num = -10
abs_value = abs(num)
print("Absolute value of -10 is {}".format(abs_value))
Absolute value of -10 is 10
num_float = -5.325
abs_value = abs(num_float)
print("Absolute value of -5.325 is {}".format(abs_value))
Absolute value of -5.325 is 5.325
complex = (3 - 4j)
print("Magnitude of 3 - 4j is: {}".format(abs(complex)))
Magnitude of 3 - 4j is: 5
all(itrable)
all() returns True if all elements of the iterables are true.
iterable_1 = [1, 2, 3, 4, 5]
all(iterable_1)
True
iterable_2 = [0, 1, 2, 3, 4, 5]
all(iterable_2)
False
any(itrable)
any(iterable) returns True if any elements in iterable is true.
iterable = [0, False, None, 1]
any(iterable)
True
iterable = [0, False, None]
any(iterable)
False
ascii(object) or repr(object)
ascii(object) return a string containing a printable representation of an object, but escape the non-ASCII characters in the string.
normal_string = 'Hello World'
print(ascii(normal_string))
non_ascii_string = 'Hellö Wörld'
print(ascii(non_ascii_string))
print('Hell\xf6 W\xf6rld')
Hello World Hell\xf6 W\xf6rld Hellö Wörld
bin(x)
bin(x) returns binary string representation of any integer number, it is prefixed with "0b".
bin(111)
'0b1101111'
bin(9999999)
'0b100110001001011001111111'
bool(x)
The bool() method converts a value to Boolean (True or False) using the standard truth testing procedure.
bool(1)
True
bool(0)
False
breakpoint(*args, **kwargs)
This function drops you into the debugger at the call site. Specifically, it calls sys.breakpointhook(), passing args and kws straight through. By default, sys.breakpointhook() calls pdb.set_trace() expecting no arguments. In this case, it is purely a convenience function so you don’t have to explicitly import pdb or type as much code to enter the debugger. Python sys.breakpointhook() function uses environment variable PYTHONBREAKPOINT to configure the debugger. If unset, default PDB debugger is used. If it’s set to “0” then the function returns immediately and no code debugging is performed. It’s very helpful when we want to run our code without debugging.
def hello():
a = 10
print("Hello")
breakpoint()
print("Done")
hello() Hello (5)hello() (Pdb) print(a) 10 (Pdb) c Done
bytearray([source[, encoding[, errors]]])
Return a new array of bytes. The bytearray class is a mutable sequence of integers in the range 0 <= x < 256.
The optional source parameter can be used to initialize the array in a few different ways:
* If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().
* If it is an integer, the array will have that size and will be initialized with null bytes.
* If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.
* If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.
* Without an argument, an array of size 0 is created.
bytearray(iterable_of_ints) -> bytearray
bytearray(string, encoding[, errors]) -> bytearray
bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer
bytearray(int) -> bytes array of size given by the parameter initialized with null bytes
bytearray() -> empty bytes array
Construct a mutable bytearray object from:
- an iterable yielding integers in range(256)
- a text string encoded using the specified encoding
- a bytes or a buffer object
- any object implementing the buffer API.
- an integer
b = bytearray()
print(b)
bytearray(b'')
b = bytearray('abc', 'UTF-8')
print(b)
b[1] = 65
print(b)
bytearray(b'abc') bytearray(b'aAc')
b = bytearray(5)
print(b)
bytearray(b'\x00\x00\x00\x00\x00')
bytes([source[, encoding[, errors]]])
Return a new “bytes” object, which is an immutable sequence of integers in the range 0 <= x < 256. bytes is an immutable version of bytearray – it has the same non-mutating methods and the same indexing and slicing behavior.
bytes(iterable_of_ints) -> bytes
bytes(string, encoding[, errors]) -> bytes
bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
bytes(int) -> bytes object of size given by the parameter initialized with null bytes
bytes() -> empty bytes object
Construct an immutable array of bytes from:
- an iterable yielding integers in range(256)
- a text string encoded using the specified encoding
- any object implementing the buffer API.
b = bytes()
print(b)
b''
b = bytes('xyz', 'UTF-8')
print(b)
b'xyz'
b[1] = 65
Original exception was: Traceback (most recent call last): File "", line 3, in TypeError: 'bytes' object does not support item assignment
b = bytes(5)
print(b)
b'\x00\x00\x00\x00\x00'
callable(object)
Return True if the object argument appears callable, False if not. If this returns True, it is still possible that a call fails, but if it is False, calling object will never succeed.
Note that classes are callable, as are instances of classes with a __call__() method.
def hello():
print("hello")
callable(hello)
True
class Hello():
def __init__(self):
self.a = 10
hello = Hello()
callable(Hello)
True
callable(hello)
False
class Hello():
def __init__(self):
self.a = 10
def __call__(self, *args, **kwargs):
print(self.a)
h = Hello()
callable(Hello)
True
callable(h)
True
chr(i)
Return the string representing a character whose Unicode code point is the integer i. For example, chr(97) returns the string 'a', while chr(8364) returns the string '€'. This is the inverse of ord(). The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base 16). ValueError will be raised if i is outside that range.
print(chr(55))
print(chr(85))
print(chr(1050))
'7'
'U'
'K'
ord()
Python ord() function takes string argument of a single Unicode character and return its integer Unicode code point value. Let’s look at some examples of using ord() function. This is inverse of chr().
print(ord('7'))
print(ord('U'))
print(ord('K'))
55
85
1050
@classmethod
Transform a method into a class method. A class method receives the class as implicit first argument, just like an instance method receives the instance.
- classmethod(function) -> method
- Convert a function to be a class method.
class Hello():
def __init__(self, a):
self.a = a
@classmethod
def print_hello(cls):
print("hello")
print(cls)
Hello(10).print_hello()
hello
<class 'main.Hello'>
h = Hello(10)
h.print_hello()
hello
<class 'main.Hello'>
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
Compile the source into a code or AST object. Code objects can be executed by exec() or eval(). source can either be a normal string, a byte string, or an AST object.
code_str = "x=10\ny=5\nprint(sum([x, y]))"
code_obj = compile(code_str, "sum.py", "exec")
code_obj
exec(code_obj)
code_str = "x=10\ny=5\nprint(sum([x, y]))"
code_obj = compile(code_str, "
sum.py", "exec")
code_obj
<code object
at 0x7ff39d4c0f60, file "sum.py", line 1>
exec(code_obj)
15
complex([real[, imag]])
Return a complex number with the value real + imag*1j or convert a string or number to a complex number. If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric type (including complex). If imag is omitted, it defaults to zero and the constructor serves as a numeric conversion like int and float. If both arguments are omitted, returns 0j.
c = complex()
print(type(c))
print(c)
complex(2, 1)
complex(1.5, -5.1)
complex(0xF)
complex(0b1010, -1)
0j
(2+1j)
(1.5-5.1j)
(15+0j)
(10-1j)
c = complex(2, "-2j")
TypeError: complex() second arg can't be a string
delattr(object, name)
The function deletes the named attribute, provided the object allows it. For example, delattr(x, 'foobar') is equivalent to del x.foobar.
class Hello():
def __init__(self):
self.x = 10
self.y = 20
h = Hello()
h.x
10
h.y
20
delattr(h, "x")
h.x
AttributeError: 'Hello' object has no attribute 'x'
dict(kwarg)
Create a new dictionary. The dict object is the dictionary class.
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict()
dict({"A": 1, "B": 2, "C": 3})
{}
{"A": 1, "B": 2, "C": 3}
dir([object])
Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.
The default dir() mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:
- If the object is a module object, the list contains the names of the module’s attributes.
- If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.
- Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.
dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
import os
dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'os']
from os import path
dir(path)
['__\all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_get_sep', '_joinrealpath', '_varprog', '_varprogb', 'abspath', 'altsep', 'basename', 'commonpath', 'commonprefix', 'curdir', 'defpath', 'devnull', 'dirname', 'exists', 'expanduser', 'expandvars', 'extsep', 'genericpath', 'getatime', 'getctime', 'getmtime', 'getsize', 'isabs', 'isdir', 'isfile', 'islink', 'ismount', 'join', 'lexists', 'normcase', 'normpath', 'os', 'pardir', 'pathsep', 'realpath', 'relpath', 'samefile', 'sameopenfile', 'samestat', 'sep', 'split', 'splitdrive', 'splitext', 'stat', 'supports_unicode_filenames', 'sys']
divmod(a, b)
Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using integer division. With mixed operand types, the rules for binary arithmetic operators apply. For integers, the result is the same as (a // b, a % b). For floating point numbers the result is (q, a % b), where q is usually math.floor(a / b) but may be 1 less than that. In any case q * b + a % b is very close to a, if a % b is non-zero it has the same sign as b, and 0 <= abs(a % b) < abs(b).
print("divmod(2, 3) => ", divmod(2, 3))
divmod(2, 3) => (0, 2)
(2//3, 2%3)
(0, 2)
enumerate(iterable, start=0)
Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The __next__() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.
mylist = ["a", "b", "c", "d"]
for i in enumerate(mylist):
print(i)
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
eval(expression[, globals[, locals]])
The arguments are a string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object. The expression argument is parsed and evaluated as a Python expression using the globals and locals dictionaries as global and local namespace.
This function can also be used to execute arbitrary code objects (such as those created by compile()). In this case pass a code object instead of a string. If the code object has been compiled with 'exec' as the mode argument, eval()’s return value will be None.
y = 10
print("Y * 2 => ", eval('Y *2'))
y * 2 => 20
exec(object[, globals[, locals]])
This function supports dynamic execution of Python code. object must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). 1 If it is a code object, it is simply executed. In all cases, the code that’s executed is expected to be valid as file input. Be aware that the return and yield statements may not be used outside of function definitions even within the context of code passed to the exec() function. The return value is None.
exec('a=2;b=3;print("a + b => ", a+b)')
exec('import os;print(os.getcwd())')
a + b => 5
/home/mylinux
filter(function, iterable)
Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed. Note that filter(function, iterable) is equivalent to the generator expression (item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is None.
mylist = ["a", "b", "c", "d"]
func = lambda x:x!="a"
list(filter(func, mylist))
['b', 'c', 'd']
float([x])
Return a floating point number constructed from a number or string x. If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded in whitespace. The optional sign may be '+' or '-'; a '+' sign has no effect on the value produced.
print(float(3))
print(float(13))
print(float("-198.223"))
print(float("99a"))
3.0
13.0
-198.223
ValueError: could not convert string to float: '99a'
format(value[, format_spec])
Convert a value to a “formatted” representation, as controlled by format_spec. The interpretation of format_spec will depend on the type of the value argument, however there is a standard formatting syntax that is used by most built-in types.
print(format(123, "d"))
print(format(123.4567898, "f"))
print(format(12, "b"))
123
123
frozenset([iterable])
Return a new frozenset object, optionally with elements taken from iterable. frozenset is a built-in class. Frozen set is just an immutable version of a Python set object. While elements of a set can be modified at any time, elements of frozen set remains the same after creation.
mylist = ["A", "B", "C", "D", "E"]
fset = frozenset(mylist)
empty_fset = frozenset()
print("mylist Frozen Set is => ", fset)
print("Empty Frozen Set is => ", empty_fset)
mylist Frozen Set is => frozenset({'A', 'C', 'B', 'D', 'E'})
Empty Frozen Set is => frozenset()
getattr(object, name[, default])
Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.
class Person:
name = "john"
age = 25
person = Person()
print("getattr(person, 'age') => ", getattr(person, "age"))
print("getattr(person, 'name') => ", getattr(person, "name"))
print("getattr(person, 'sex') => ", getattr(person, "sex", "Male"))
print("getattr(person, 'ssn') => ", getattr(person, "ssn"))
getattr(person, 'age') => 25
getattr(person, 'name') => john
getattr(person, 'sex') => Male
AttributeError: 'Person' object has no attribute 'ssn'
globals()
Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called). A symbol table is a data structure maintained by a compiler which contains all necessary information about the program. These include variable names, methods, classes, etc. There are mainly two kinds of symbol table. Local symbol table. Global symbol table. Local symbol table stores all information related to the local scope of the program, and is accessed in Python using locals() method. The local scope could be within a function, within a class, etc. Likewise, a Global symbol table stores all information related to the global scope of the program, and is accessed in Python using globals() method. The global scope contains all functions, variables which are not associated to any class or function.
mylist = ["A", "B", "C", "D", "E"]
globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'mylist': ['A', 'B', 'C', 'D', 'E']}
hasattr(object, name)
The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. The hasattr() is called by getattr() to check to see if AttributeError is to be raised or not.
class Person:
name = "john"
age = 25
person = Person()
print("hasattr(person, 'age') => ", hasattr(person, "age"))
print("hasattr(person, 'name') => ", hasattr(person, "name"))
print("hasattr(person, 'sex') => ", hasattr(person, "sex"))
hasattr(person, 'age') => True
hasattr(person, 'name') => True
hasattr(person, 'sex') => False
hash(object)
Return the hash value of the object (if it has one). Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup. Numeric values that compare equal have the same hash value (even if they are of different types, as is the case for 1 and 1.0).
x = 125
print("Hash value of x is => ", hash(x))
y = 14.856
print("Hash value of y is => ", hash(y))
mylist = ("A", "B", "C", "D", "E")
print("Hash value of mylist is => ", hash(mylist))
class Person:
def __init__(self, age, name):
self.age = age
self.name = name
person_1 = Person(25, "john")
person_2 = Person(25, "john")
person_3 = Person(35, "Jack")
print("Hash value of person_1 is => ", hash(person_1))
print("Hash value of person_2 is => ", hash(person_2))
print("Hash value of person_3 is => ", hash(person_3))
Hash value of x is => 125
Hash value of y is => 1973801615886921742
Hash value of mylist is => 1232786484201484235
Hash value of person_1 is => 8791149213416
Hash value of person_2 is => 8791149852139
Hash value of person_3 is => 8791149217157
help([object])
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.
help(list)
help(dict)
help(set)
import os
help(os)
hex(x)
Convert an integer number to a lowercase hexadecimal string prefixed with “0x”. If x is not a Python int object, it has to define an __index__() method that returns an integer.
x = 125
z = -55
y = 255.333
print("Hex value of x is => ", hex(x))
print("Hex value of z is => ", hex(z))
print("Hex value of y is => ", float.hex(y))
Hex value of x is => 0x7d
Hex value of z is => -0x37
Hex value of y is => 0x1.feaa7ef9db22dp+7
id(object)
Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.
x = 125
y = -5555
z = 96.742
class Person:
age = 25
name = "john"
person = Person()
print("Id of x is => ", id(x))
print("Id of y is => ", id(y))
print("Id of z is => ", id(z))
print("Id of person is => ", id(person))
Id of x is => 11500608
Id of y is => 140658361058416
Id of z is => 140658387585232
Id of person is => 140658398336768
input([prompt])
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.
name = input("Enter Your Name: ")
age = input("Enter Your Age: ")
print(name)
print(age)
Enter Your Name: john
Enter Your Age: 25
john
25
int([x])
Return an integer object constructed from a number or string x, or return 0 if no arguments are given. If x defines __int__(), int(x) returns x.__int__(). If x defines __index__(), it returns x.__index__(). If x defines __trunc__(), it returns x.__trunc__(). For floating point numbers, this truncates towards zero. If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in radix base.
x = 10
y = 9856
z = 95.85
a = "147"
print("Value of x is => ", int(x))
print("Value of y is => ", int(y))
print("Value of z is => ", int(z))
print("Value of a is => ", int(a))
class Person:
age = 36
def __index__(self):
return self.age
def __int__(self):
return self.age
p = Person()
print("Value of p is => ", int(p))
Value of x is => 10
Value of y is => 9856
Value of z is => 95
Value of a is => 147
Value of p is => 36
isinstance(object, classinfo)
Return True if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. If object is not an object of the given type, the function always returns False.
x = 10
y = "Apple"
z = [1, 2, 3, 4]
a = None
print("Value of x is type of int => ", isinstance(x, int))
print("Value of y is type of string => ", isinstance(y, str))
print("Value of z is type of list => ", isinstance(z, list))
print("Value of a is type of list => ", isinstance(a, list))
Value of x is of type int => True
Value of y is of type string => True
Value of z is of type list => True
Value of a is type of list => False
issubclass(class, classinfo)
Return True if class is a subclass (direct, indirect or virtual) of classinfo. A class is considered a subclass of itself. classinfo may be a tuple of class objects, in which case every entry in classinfo will be checked. In any other case, a TypeError exception is raised.
class Age:
def __init__(self):
self.age = 36
class Person(Age):
def __init__(self):
Age.__init__(self)
self.name = "John"
age = Age()
person = Person()
print("Class Person is subclass of class Age => ", issubclass(Person, Age))
print("Class Person is subclass of class list => ", issubclass(Person, list))
print("Class Person is subclass of class list or Age => ", issubclass(Person, (list, Age)))
Class Person is subclass of class Age => True
Class Person is subclass of class list => True
Class Person is subclass of class list or Age => True
iter(object[, sentinel])
Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, object must be a collection object which supports the iteration protocol (the __iter__() method), or it must support the sequence protocol (the __getitem__() method with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised.
mylist = ["A", "B", "C", "D"]
iterobj = iter(mylist)
print(next(iterobj))
print(next(iterobj))
print(next(iterobj))
print(next(iterobj))
A
B
C
D
class MyAge:
def __init__(self):
self.age = 36
def __iter__(self):
return self
def __next__(self):
self.age += 1
return self.age
myage = MyAge()
print("Age after one year => ", next(myage))
print("Age after two year => ", next(myage))
print("Age after three year => ", next(myage))
Age after one year => 37
Age after two year => 38
Age after three year => 39
len(s)
Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).
mylist = ["A", "B", "C"]
mytuple = (1, 2, 3, 4, 5, 6, 7, 8, 9)
myrange = range(20)
print("Length of mylist is => ", len(mylist))
print("Length of mytuple is => ", len(mytuple))
print("Length of myrange is => ", len(myrange))
Length of mylist is => 3
Length of mytuple is => 9
Length of myrange is => 20
class Employees:
def __init__(self, count):
self.count = count
def __len__(self):
return self.count
office_1 = Employees(10)
office_2 = Employees(20)
print("Total employees in office 1 is => ", len(office_1))
print("Total employees in office 2 is => ", len(office_2))
Total employees in office 1 is => 10
Total employees in office 2 is => 20
list([iterable])
list is built-in mutable sequence. If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.
a = list()
print("value of a is => ", a)
b = list("12356789")
print("Value of b is => ", b)
value of a is => []
Value of b is => ['1', '2', '3', '5', '6', '7', '8', '9']
locals()
Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks. Note that at the module level, locals() and globals() are the same dictionary. Local symbol table stores all information related to the local scope of the program, and is accessed in Python using locals() method.
mylist = range(10)
locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class 'frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins_': <module 'builtins' (built-in)>, 'mylist': range(0, 10)}
map(function, iterable, ...)
Return an iterator that applies function to every item of iterable, yielding the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel.
def sub(x):
return x - 1
mylist = [10, 20, 30, 40]
mynewlist = list(map(sub, mylist))
print(mynewlist)
[9, 19, 29, 39]
max(iterable, [, key, default])
Return the largest item in an iterable or the largest of two or more arguments. If one positional argument is provided, it should be an iterable. The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned.
mylist = [10, 15, 75, 22, 56, 85, 44, 55, 72]
print("Maximum value of mylist is => ", max(mylist))
def modulus(x):
return x % 10
print("Maximum value of mylist is => ", max(mylist, key=modulus))
Maximum value of mylist is => 85 Maximum value of mylist is => 56
memoryview(obj)
Buffer protocol provides a way to access the internal data of an object. This internal data is a memory array or a buffer. Buffer protocol allows one object to expose its internal data (buffers) and the other to access those buffers without intermediate copying. This protocol is only accessible to us at the C-API level and not using our normal code base. So, in order to expose the same protocol to normal Python code base, memory views are present.
Memory view is a safe way to expose the buffer protocol in Python. It allows you to access the internal buffers of an object by creating a memory view object.
We need to remember that whenever we perform some action on an object (call a function of an object, slice an array), we (or Python) need to create a copy of the object. If we have a large data to work with (eg. binary data of an image), we would unnecessarily create copies of huge chunks of data, which serves almost no use. Using buffer protocol, we can give another object access to use/modify the large data without copying it. This makes the program use less memory and increases the execution speed.
mylist = [10, 15, 75, 22, 56, 85, 44, 55, 72]
b = bytearray(mylist)
mv = memoryview(b)
print(mv[0])
print(list(mv))
10 [10, 15, 75, 22, 56, 85, 44, 55, 72]
min(iterable, [, key, default])
Return the smallest item in an iterable or the smallest of two or more arguments. If one positional argument is provided, it should be an iterable. The smallest item in the iterable is returned. If two or more positional arguments are provided, the smallest of the positional arguments is returned. There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for list.sort(). The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised. If multiple items are minimal, the function returns the first one encountered.
mylist = [10, 15, 75, 22, 56, 85, 44, 55, 72]
print("Minimum value of mylist is => ", min(mylist))
def modulus(x):
return x % 10
print("Minimum value of mylist is => ", min(mylist, key=modulus))
Minimum value of mylist is => 10 Minimum value of mylist is => 10
next(iterator[, default])
Retrieve the next item from the iterator by calling its __next__() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.
mylist = [10, 15, 75]
it = iter(mylist)
print(next(it))
print(next(it))
print(next(it))
print(next(it))
mylist = [10, 15, 75]
it = iter(mylist)
print(next(it, 0))
print(next(it, 0))
print(next(it, 0))
print(next(it, 0))
10
15
75
StopIteration
10
15
75
0
object
Return a new featureless object. object is a base for all classes. It has the methods that are common to all instances of Python classes. This function does not accept any arguments. object does not have a \_\_dict\_\_, so you can’t assign arbitrary attributes to an instance of the object class.
obj = object()
print(obj)
type(obj)
dir(obj)
<object object at 0x7f8f4472be70>
<class 'object'>
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
oct(x)
Convert an integer number to an octal string prefixed with “0o”. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.
x = 10
y = 20
print(oct(x))
print(oct(y))
class Age():
def __init__(self):
self.age = 25
def __index__(self):
return self.age
def __int__(self):
return self.age
a = Age()
print(oct(a))
print(oct(25))
0o12 0o24 0o31 0o31
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised. file is a path-like object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False.)
mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode. Other common values are 'w' for writing (truncating the file if it already exists), 'x' for exclusive creation and 'a' for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position). In text mode, if encoding is not specified the encoding used is platform dependent: locale.getpreferredencoding(False) is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave encoding unspecified.) The available modes are:
'r' => open for reading (default)
'w' => open for writing, truncating the file first
'x' => open for exclusive creation, failing if the file already exists
'a' => open for writing, appending to the end of the file if it exists
'b' => binary mode
't' => text mode (default)
'+' => open for updating (reading and writing)
The default mode is 'r' (open for reading text, synonym of 'rt'). Modes 'w+' and 'w+b' open and truncate the file. Modes 'r+' and 'r+b' open the file with no truncation.
As mentioned in the Overview, Python distinguishes between binary and text I/O. Files opened in binary mode (including 'b' in the mode argument) return contents as bytes objects without any decoding. In text mode (the default, or when 't' is included in the mode argument), the contents of the file are returned as str, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given.
There is an additional mode character permitted, 'U', which no longer has any effect, and is considered deprecated. It previously enabled universal newlines in text mode, which became the default behaviour in Python 3.0.
Buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size in bytes of a fixed-size chunk buffer. When no buffering argument is given, the default buffering policy works as follows:
Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device’s “block size” and falling back on io.DEFAULT_BUFFER_SIZE. On many systems, the buffer will typically be 4096 or 8192 bytes long.
“Interactive” text files (files for which isatty() returns True) use line buffering. Other text files use the policy described above for binary files.
Encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever locale.getpreferredencoding() returns), but any text encoding supported by Python can be used.
Errors is an optional string that specifies how encoding and decoding errors are to be handled—this cannot be used in binary mode. A variety of standard error handlers are available (listed under Error Handlers), though any error handling name that has been registered with codecs.register_error() is also valid. The standard names include:
'strict' to raise a ValueError exception if there is an encoding error. The default value of None has the same effect.
'ignore' ignores errors. Note that ignoring encoding errors can lead to data loss.
'replace' causes a replacement marker (such as '?') to be inserted where there is malformed data.
'surrogateescape' will represent any incorrect bytes as code points in the Unicode Private Use Area ranging from U+DC80 to U+DCFF. These private code points will then be turned back into the same bytes when the surrogateescape error handler is used when writing data. This is useful for processing files in an unknown encoding.
'xmlcharrefreplace' is only supported when writing to a file. Characters not supported by the encoding are replaced with the appropriate XML character reference &#nnn;.
'backslashreplace' replaces malformed data by Python’s backslashed escape sequences.
'namereplace' (also only supported when writing) replaces unsupported characters with \N{...} escape sequences.
Newline controls how universal newlines mode works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows:
When reading input from the stream, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.
When writing output to the stream, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '' or '\n', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string.
If closefd is False and a file descriptor rather than a filename was given, the underlying file descriptor will be kept open when the file is closed. If a filename is given closefd must be True (the default) otherwise an error will be raised.
A custom opener can be used by passing a callable as opener. The underlying file descriptor for the file object is then obtained by calling opener with (file, flags). opener must return an open file descriptor (passing os.open as opener results in functionality similar to passing None).
The newly created file is non-inheritable.
f = open("test.txt", mode='r')
f = open("test.txt", mode = 'w')
f = open("test.txt", mode = 'a')
f = open("test.txt", mode = 'r', encoding='utf-8')
ord(c)
Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example, ord('a') returns the integer 97 and ord('€') (Euro sign) returns 8364. This is the inverse of chr().
print(ord("a"))
print(ord("€"))
97
8364
pow(base, exp[, mod])
Return base to the power exp; if mod is present, return base to the power exp, modulo mod (computed more efficiently than pow(base, exp) % mod). The two-argument form pow(base, exp) is equivalent to using the power operator: base**exp.
The arguments must have numeric types. With mixed operand types, the coercion rules for binary arithmetic operators apply. For int operands, the result has the same type as the operands (after coercion) unless the second argument is negative; in that case, all arguments are converted to float and a float result is delivered. For example, 10**2 returns 100, but 10**-2 returns 0.01.
For int operands base and exp, if mod is present, mod must also be of integer type and mod must be nonzero. If mod is present and exp is negative, base must be relatively prime to mod. In that case, pow(inv_base, -exp, mod) is returned, where inv_base is an inverse to base modulo mod.
pow(38, -1, mod=97)
23 * 38 % 97 == 1
23
True
print(objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Print objects to the text stream file, separated by sep and followed by end. sep, end, file and flush, if present, must be given as keyword arguments.
All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.
The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead.
Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.
print("This is Python", end="\n\n")
This is Python
property(fget=None, fset=None, fdel=None, doc=None)
Return a property attribute. fget is a function for getting an attribute value. fset is a function for setting an attribute value. fdel is a function for deleting an attribute value. And doc creates a docstring for the attribute.
class C:
def __init__(self):
self._x = None
def getx(self):
return self._x
def setx(self, value):
self._x = value
def delx(self):
del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")
c = C()
c.setx("Test")
c.getx()
Test
class Car:
def __init__(self, wheels):
self._wheels = wheels
@property
def wheels(self):
return self._wheels
car = Car(4)
car.wheels
4
range(start, stop[, step])
The range() type returns an immutable sequence of numbers between the given start integer to the stop integer.
l = range(1, 10)
print(list(l))
l = range(1, 10, 2)
print(list(l))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 3, 5, 7, 9]
repr(object)
Return a string containing a printable representation of an object. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.
class Car:
def __init__(self):
self.name = "CyberTruck"
def __repr__(self):
return self.name
car = Car()
repr(car)
CyberTruck
reversed(seq)
Return a reverse iterator. seq must be an object which has a __reversed__() method or supports the sequence protocol (the __len__() method and the __getitem__() method with integer arguments starting at 0).
p = "Python"
print(list(reversed(p)))
mylist = [1, 2, 3, 4]
print(list(reversed(mylist)))
['n', 'o', 'h', 't', 'y', 'P']
, [4, 3, 2, 1]
round(number[, ndigits])
Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.
round(10.5)
round(10.555, 1)
10
10.6
set([iterable])
Return a new set object, optionally with elements taken from iterable. set is a built-in class.
mylist = [1, 2, 3, 3, 3, 4]
mynewlist = list(set(mylist))
mynewlist
[1, 2, 3, 4]
setattr(object, name, value)
This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.
class Car:
def __init__(self):
self.wheels = None
car = Car()
setattr(car, "wheels", 4)
car.wheels
4
slice(start, stop[, step])
Return a slice object representing the set of indices specified by range(start, stop, step). The start and step arguments default to None. Slice objects have read-only data attributes start, stop and step which merely return the argument values (or their default). They have no other explicit functionality; however they are used by Numerical Python and other third party extensions. Slice objects are also generated when extended indexing syntax is used. For example: a[start:stop:step] or a[start:stop, i]
sobj = slice(0, 2, 1)
s = "Python"
s[sobj]
Py
sorted(iterable, , key=None, reverse=False)
Return a new sorted list from the items in iterable. Has two optional arguments which must be specified as keyword arguments. key specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example, key=str.lower). The default value is None (compare the elements directly). reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.
mylist = [1, 5, 2, 4]
sorted(mylist)
sorted(mylist, reverse=True)
[1, 2, 4, 5]
[5, 4, 2, 1]
@staticmethod
Transform a method into a static method. A static method does not receive an implicit first argument.
class Car:
@staticmethod
def wheels(wheels):
return int(wheels)
@staticmethod
def name(name):
return name.upper()
Car.wheels("4")
Car.name("cybertruck")
4
CYBERTRUCK
class str(object='')
Return a str version of object.
x = "car"
str(x)
y = 444
str(y)
class Car:
def __init__(self):
self.name = "CyberTruck"
def __str__(self):
return "<Car 'CyberTruck'>"
car = Car()
str(car)
'car'
'444'
"<Car 'CyberTruck'>"
sum(iterable, /, start=0)
Sums start and the items of an iterable from left to right and returns the total. The iterable’s items are normally numbers, and the start value is not allowed to be a string.
mylist = [1, 2, 3]
sum(mylist)
6
super([type[, object-or-type]])
Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The object-or-type determines the method resolution order to be searched. The search starts from the class right after the type.
There are two typical use cases for super. In a class hierarchy with single inheritance, super can be used to refer to parent classes without naming them explicitly, thus making the code more maintainable. This use closely parallels the use of super in other programming languages.
The second use case is to support cooperative multiple inheritance in a dynamic execution environment. This use case is unique to Python and is not found in statically compiled languages or languages that only support single inheritance. This makes it possible to implement “diamond diagrams” where multiple base classes implement the same method. Good design dictates that this method have the same calling signature in every case (because the order of calls is determined at runtime, because that order adapts to changes in the class hierarchy, and because that order can include sibling classes that are unknown prior to runtime).
class Engine:
def engine(self):
return "Patrol Engine"
class Car(Engine):
def __init__(self):
self.engine = super().engine()
car = Car()
car.engine
'Patrol Engine'
tuple([iterable])
tuple is actually an immutable sequence type.
s = "Python"
t = tuple(s)
print(t)
mylist = [1, 2, 3, 4]
t = tuple(mylist)
print(t)
('P', 'y', 't', 'h', 'o', 'n')
(1, 2, 3, 4)
type(object)
With one argument, return the type of an object. The return value is a type object and generally the same object as returned by object.__class__.
x = 10
type(x)
y = "ABC"
type(y)
class Car:
def __init__(self):
self.name = "CyberTruck"
car = Car()
type(car)
<class 'int'> <class 'str'> <class 'main.Car'>
vars([object])
Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute.
class Car:
def __init__(self):
self.wheels = 4
self.name = "CyberTruck"
car = Car()
vars(car)
{'wheels': 4, 'name': 'CyberTruck'}
zip(iterables)
Make an iterator that aggregates elements from each of the iterables. Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator.
x = ["X", "Y", "Z"]
y = [1, 2, 3]
mylist = list(zip(x, y))
mylist
[('X', 1), ('Y', 2), ('Z', 3)]
import(name, globals=None, locals=None, fromlist=(), level=0)
This function is invoked by the import statement. It can be replaced (by importing the builtins module and assigning to builtins.__import__) in order to change semantics of the import statement, but doing so is strongly discouraged as it is usually simpler to use import hooks to attain the same goals and does not cause issues with code which assumes the default import implementation is in use.
* name - name of the module you want to import
* globals and locals - determines how to interpert name
* fromlist - objects or submodules that should be imported by name
* level - specifies whether to use absolute or relative imports
os = __import__("os", globals(), locals(), [], 0)
print(os.getcwd())
/home/mylinux
No comments:
Post a Comment