Builtin – Built-in Functions and Exceptions
All built-in functions and exceptions are described here. They are also available through the builtins module.
Functions
- abs()
Return the absolute value of a number. The argument can be an integer or a float. If the argument is a complex number, its magnitude is returned.
- all()
Return True if all elements of the iterable are true (or if the iterable is empty).
Equivalent to:
def all(iterable):
for element in iterable:
if not element:
return False
return True
- any()
Return True if any element of the iterable is true. If the iterable is empty, return False.
Equivalent to:
def any(iterable):
for element in iterable:
if element:
return True
return False
- bin()
Convert an integer to a binary string prefixed with “0b”.
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
- class bool
Convert the given argument to a Boolean type. If no argument is given, returns False.
>>>bool()
False
>>> bool(0)
False
>>> bool(1)
True
>>> bool(None)
False
- class bytearray
Return a new bytes array. The bytearray class is a mutable sequence containing integers in the range 0 <= x < 256.
>>>bytearray()
bytearray(b'')
>>> bytearray([1,2,3])
bytearray(b'\x01\x02\x03')
>>> bytearray('mpython')
bytearray(b'mpython')
>>>
- class bytes
The bytes function returns a new bytes object, which is an immutable sequence of integers in the range 0 <= x < 256. It is the immutable version of bytearray. See CPython documentation: bytes
>>>a = bytes([1,2,3,4])
>>> a
b'\x01\x02\x03\x04'
>>> type(a)
<class 'bytes'>
>>>
>>> a = bytes('hello')
>>>
>>> a
b'hello'
>>> type(a)
<class 'bytes'>
>>>
- callable()
Check whether an object is callable. If it returns True, the object might still fail when called; but if it returns False, calling the object will never succeed.
>>>callable(0)
False
>>> callable("mpython")
False
>>> def add(a, b):
... return a + b
...
>>> callable(add) # Function returns True
True
>>> class A: # Class
... def method(self):
... return 0
...
>>> callable(A) # Class returns True
True
>>> a = A()
>>> callable(a) # Does not implement __call__, returns False
False
>>> class B:
... def __call__(self):
... return 0
...
>>> callable(B)
True
>>> b = B()
>>> callable(b) # Implements __call__, returns True
True
- chr()
Return the string representing a character whose Unicode code point is the integer i.
>>>chr(0x30)
'0'
>>> chr(97)
'a'
>>> chr(8364)
'€'
- @classmethod
Transform a method into a class method.
A class method receives the class as its first argument, just like an instance method receives the instance as its first argument. Use the following idiom to declare a class method:
class C:
@classmethod
def f(cls, arg1, arg2, ...): ...
The form @classmethod is called a function decorator. Class method calls can be made on the class (e.g. C.f()) or on an instance (e.g. C().f()). Instances other than their own class are ignored. If a class method is called on a derived class, the derived class object is passed as the implied first argument.
- compile(source, filename, mode[, flags[, dont_inherit]])
Compile a string into bytecode. For details see CPython documentation: compile
>>>str = "for i in range(0,10): print(i)"
>>> c = compile(str,'','exec') # Compile to bytecode object
>>> c
<code object <module> at 0x10141e0b0, file "", line 1>
>>> exec(c)
0
1
2
3
4
5
6
7
8
9
>>> str = "3 * 4 + 5"
>>> a = compile(str,'','eval')
>>> eval(a)
17
- class 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 is interpreted as a complex number and the function must be called without a second parameter. The second parameter cannot be a string. Each argument can be any numeric type (including complex). If imag is omitted, it defaults to zero and the constructor performs numeric conversion like int and float. If both arguments are omitted, returns 0j.
>>>complex(1, 2)
(1 + 2j)
>>> complex(1) # Number
(1 + 0j)
>>> complex("1") # Treated as string
(1 + 0j)
# Note: There cannot be spaces around the "+" sign, i.e. cannot write "1 + 2j", should be "1+2j", otherwise it will error
>>> complex("1+2j")
(1 + 2j)
- delattr(obj, name)
Related to setattr(). The arguments are an object and a string. The string must be the name of one of the object’s attributes. If the object allows it, the function will delete the specified attribute. For example, delattr(x, ‘foobar’) is equivalent to del x.foobar.
class Coordinate:
x = 10
y = -5
z = 0
point1 = Coordinate()
print('x = ',point1.x)
print('y = ',point1.y)
print('z = ',point1.z)
delattr(Coordinate, 'z')
print('--After deleting z attribute--')
print('x = ',point1.x)
print('y = ',point1.y)
# Triggers error
print('z = ',point1.z)
- class dict(**kwarg)
- class dict(mapping, **kwarg)
- class dict(iterable, **kwarg)
**kwargs– Keywordsmapping– Container of elements.iterable– Iterable object.
The dict() function is used to create a dictionary
>>>dict() # Create empty dictionary
{}
>>> dict(a='a', b='b', t='t') # Pass in keywords
{'a': 'a', 'b': 'b', 't': 't'}
>>> dict(zip(['one', 'two', 'three'], [1, 2, 3])) # Construct dictionary using mapping function
{'three': 3, 'two': 2, 'one': 1}
>>> dict([('one', 1), ('two', 2), ('three', 3)]) # Construct dictionary using iterable
{'three': 3, 'two': 2, 'one': 1}
>>>
- dir(object)
The dir() function without arguments returns the list of names in the current local scope. With an argument, it returns the list of valid attributes and methods of that object. If the object has a method named __dir__(), this method will be called. If the object does not contain __dir__(), the method will gather information from the object as much as possible.
object– Object, variable, or type.
- divmod()
Takes two (non-complex) numbers as arguments and returns a pair of quotient and remainder when performing integer division. For mixed operand types, the rules for binary arithmetic operators apply. For integers, the result is the same as (a // b, a % b). For floats, 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 should be very close to a; if a % b is non-zero, it has the same sign as b, and 0 <= abs(a % b) < abs(b).
>>> divmod(7, 2)
(3, 1)
>>> divmod(8, 2)
(4, 0)
>>> divmod(8, -2)
(-4, 0)
>>> divmod(3, 1.3)
(2.0, 0.4000001)
- enumerate(sequence[, start=0])
The enumerate() function combines a traversable data object (such as a list, tuple, or string) into an index sequence, listing both data and data indices. Generally used in for loops.
sequence– A sequence, iterator, or other iterable object.start– Starting index position.
>>>seq = ['one', 'two', 'three']
>>> for i, element in enumerate(seq):
... print i, element
...
0 one
1 two
2 three
- eval(expression[, globals[, locals]])
The eval() function evaluates a string expression and returns the value of the expression.
expression– Expression.globals– Variable scope, global namespace. If provided, must be a dictionary object.locals– Variable scope, local namespace. If provided, can be any mapping object.
>>>x = 7
>>> eval( '3 * x' )
21
>>> eval('pow(2,2)')
4
>>> eval('2 + 2')
4
>>> n=81
>>> eval("n + 4")
85
- exec(object[, globals[, locals]])
exec executes Python statements stored in a string or file. Compared to eval, exec can execute more complex Python code.
object: Required parameter, representing the specified Python code. It must be a string or code object. If object is a string, the string is first parsed as a set of Python statements, then executed (unless a syntax error occurs). If object is a code object, it is simply executed.globals: Optional parameter, representing the global namespace (storing global variables). If provided, must be a dictionary object.locals: Optional parameter, representing the current local namespace (storing local variables). If provided, can be any mapping object. If this parameter is omitted, it takes the same value as globals.
>>>exec('print("Hello World")')
Hello World
# Single-line statement string
>>> exec("print ('runoob.com')")
runoob.com
# Multi-line statement string
>>> exec ("""for i in range(5):
... print ("iter time: %d" % i)
... """)
iter time: 0
iter time: 1
iter time: 2
iter time: 3
iter time: 4
- filter(function, iterable)
Used to filter sequences, filtering out elements that do not meet the condition, returning an iterator object. To convert to a list, use list()
function– Judgment function.iterable– Iterable object.
Filter out all odd numbers from the list:
def is_odd(n):
return n % 2 == 1
tmplist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
newlist = list(tmplist)
print(newlist)
- class float([x])
The float() function converts integers and strings to floating point numbers.
>>>float(1)
1.0
>>> float(112)
112.0
>>> float(-123.6)
-123.6
>>> float('123') # String
123.0
- format(value[, format_spec])
String formatting function str.format(), which enhances string formatting capabilities. The format function can accept unlimited arguments, and positions need not be in order. The basic syntax uses {} and : instead of the previous %. For more detailed syntax, see CPython Format String Syntax
>>>"{} {}".format("hello", "world") # No specified position, uses default order
'hello world'
>>> "{0} {1}".format("hello", "world") # Specified position
'hello world'
>>> "{1} {0} {1}".format("hello", "world") # Specified position
'world hello world
- class frozenset([iterable])
Return a frozen set. After freezing, no elements can be added or removed from the set.
iterable– Iterable object, such as list, dict, tuple, etc.
- getattr(object, name[, default])
Return the value of an object attribute.
>>>class A(object):
... bar = 1
...
>>> a = A()
>>> getattr(a, 'bar') # Get attribute bar value
1
>>> getattr(a, 'bar2') # Attribute bar2 does not exist, triggers exception
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'bar2'
>>> getattr(a, 'bar2', 3) # Attribute bar2 does not exist, but default value is set
- globals()
The globals() function returns all global variables at the current position as a dictionary.
- hasattr(object, name)
Determine whether an object contains the corresponding attribute.
object– Object.name– String, attribute name.
class Coordinate:
x = 10
y = -5
z = 0
point1 = Coordinate()
print(hasattr(point1, 'x'))
print(hasattr(point1, 'y'))
print(hasattr(point1, 'z'))
print(hasattr(point1, 'no')) # Does not have this attribute
Output:
True
True
True
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 dictionary lookups. Numeric values of equal magnitude have the same hash value.
- help([object])
View detailed description of a function or module usage.
- hex(x)
Convert an integer to a lowercase hexadecimal string prefixed with “0x”.
>>> hex(255)
'0xff'
>>> hex(-42)
'-0x2a'
- id([object])
Get the memory address of an object.
- input([prompt])
Receive standard input data, returned as string type.
- class int([x])
- class int(x, base=10)
Convert a string or number to an integer.
x– String or number.base– Radix, default decimal
- 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. If classinfo is a tuple of object types (or multiple recursively), return True if object is an instance of any of them. If classinfo is not a type, nor a tuple of types, nor a recursive tuple of types, a TypeError exception is raised.
Difference between isinstance() and type()
type() does not consider subclasses as a parent class type; inheritance is not considered.
isinstance() considers subclasses as a parent class type; inheritance is considered.
It is recommended to use isinstance() to check if two types are the same.
- issubclass(class, classinfo)
Return True if class is a subclass (direct, indirect, or virtual) of classinfo. classinfo can be a tuple of class objects, in which case every element in classinfo will be checked. In other cases, a TypeError exception is raised.
class A:
pass
class B(A):
pass
print(issubclass(B,A)) # Returns True
- iter(object[, sentinel])
Used to generate an iterator.
object– A collection object that supports iteration.sentinel– If the second argument is passed, the object argument must be a callable object (such as a function). In this case, iter creates an iterator object that calls object each time its __next__() method is called.
>>>lst = [1, 2, 3]
>>> for i in iter(lst):
... print(i)
...
1
2
3
- len()
Return the length (number of items) of an object (string, list, tuple, etc.).
>>>str = "runoob"
>>> len(str) # String length
6
>>> l = [1,2,3,4,5]
>>> len(l) # Number of list elements
5
- class list
Convert a tuple or string to a list.
aTuple = (123, 'Google', 'baidu', 'Taobao')
list1 = list(aTuple)
print ("List elements: ", list1)
str="Hello World"
list2=list(str)
print ("List elements: ", list2)
Output:
List elements: [123, 'Google', 'Runoob', 'Taobao']
List elements: ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
- locals()
Return all local variables at the current position as a dictionary.
>>>def runoob(arg): # Two local variables: arg, z
... z = 1
... print (locals())
...
>>> runoob(4)
{'z': 1, 'arg': 4} # Returns a dictionary of name/value pairs
>>>
- map(function, iterable, ...)
map() applies the provided function to the specified sequence. Returns 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. When there are multiple iterables, the iteration stops when the shortest iterable is exhausted.
>>>def square(x) : # Calculate square
... return x ** 2
...
>>> map(square, [1,2,3,4,5]) # Calculate the square of each list element
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5]) # Using lambda anonymous function
[1, 4, 9, 16, 25]
# Given two lists, add data at the same positions
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]
- max()
Return the largest of the given arguments. Arguments can be sequences.
print ("max(80, 100, 1000) : ", max(80, 100, 1000))
print ("max(-20, 100, 400) : ", max(-20, 100, 400))
print ("max(-80, -20, -10) : ", max(-80, -20, -10))
print ("max(0, 100, -400) : ", max(0, 100, -400))
Output:
max(80, 100, 1000) : 1000
max(-20, 100, 400) : 400
max(-80, -20, -10) : -10
max(0, 100, -400) : 100
- class memoryview
Return a memory view object of the given argument. A memory view object wraps data that supports the buffer protocol, allowing Python code to access it without copying the object.
>>>v = memoryview(bytearray("abcefg"))
>>> v[1]
98
>>> v[-1]
103
>>> v[1:4]
<memoryview>
>>> bytes(v[1:4)
b'bce'
>>>
- min()
Return the smallest of the given arguments. Arguments can be sequences.
print ("min(80, 100, 1000) : ", min(80, 100, 1000))
print ("min(-20, 100, 400) : ", min(-20, 100, 400))
print ("min(-80, -20, -10) : ", min(-80, -20, -10))
print ("min(0, 100, -400) : ", min(0, 100, -400))
Output:
min(80, 100, 1000) : 80
min(-20, 100, 400) : -20
min(-80, -20, -10) : -80
min(0, 100, -400) : -400
- next(iterator[, default])
Return the next item from the iterator. Gets the next element by calling the iterator’s __next__() method. If the iterator is exhausted, returns the given default; if no default is provided, raises StopIteration.
# First get the Iterator object:
it = iter([1, 2, 3, 4, 5])
# Loop:
while True:
try:
# Get the next value:
x = next(it)
print(x)
except StopIteration:
# Exit loop when StopIteration is encountered
break
- class object
- oct()
Convert an integer to an octal string.
>>>oct(10)
'012'
>>> oct(20)
'024'
>>> oct(15)
'017'
>>>
- open()
The open() method opens a file and returns a file object. This function is needed for all file processing operations. If the file cannot be opened, an OSError is raised. Note: When using open(), always ensure the file object is closed by calling the close() method.
The common form of the open() function takes two arguments: file name (file) and mode (mode):
open(file, mode='r')
mode is an optional string specifying the file opening mode. The default value is ‘r’, which means open for reading in text mode. Other common modes are: write ‘w’ (truncating existing files); exclusive creation ‘x’; append ‘a’ (on some Unix systems, all writes append to the end of the file regardless of the current file pointer position). Available modes are:
Mode |
Description |
‘r’ |
Read (default) |
‘w’ |
Write, truncating the file first |
‘x’ |
Exclusive creation, failing if the file already exists |
‘a’ |
Write, appending to the end if the file exists |
‘a’ |
Write, appending to the end if the file exists |
‘b’ |
Binary mode |
‘t’ |
Text mode (default) |
‘+’ |
Update disk file (read and write) |
The default mode is ‘r’ (open and read text, same as ‘rt’). For binary writing, ‘w+b’ mode opens and truncates the file to 0 bytes; ‘r+b’ does not truncate.
- ord(c)
This is the inverse of chr(). It takes a string (Unicode character) as an argument and returns an integer representing the corresponding Unicode code point.
>>>ord('a')
97
>>> ord('€')
8364
>>>
- pow(x, y[, z])
Return the value of x raised to the power of y.
print ("pow(100, 2) : ", pow(100, 2))
print ("pow(100, -2) : ", pow(100, -2))
print ("pow(2, 4) : ", pow(2, 4))
print ("pow(3, 0) : ", pow(3, 0))
Output:
pow(100, 2) : 10000
pow(100, -2) : 0.0001
pow(2, 4) : 16
pow(3, 0) : 1
- print(*objects, sep=' ', end='\n', file=sys.stdout)
Used for printing output, the most common function.
objects: Plural, indicating multiple objects can be output at once. When outputting multiple objects, they must be separated by commas.
sep: Used to separate multiple objects, default is a space.
end: Used to set what to end with. Default is newline n, can be changed to other strings.
file: The file object to write to.
>>> print(1)
1
>>> print("Hello World")
Hello World
>>> a = 1
>>> b = 'w3cschool'
>>> print(a,b)
1 w3cschool
>>> print("aaa""bbb")
aaabbb
>>> print("aaa","bbb")
aaa bbb
>>>
>>> print("www","w3cschool","cn",sep=".") # Set separator
www.w3cschool.cn
- @property
The property() function returns attribute values in new-style classes. Using property as a decorator conveniently creates read-only attributes:
The getter, setter, and deleter methods of property can also be used as decorators:
class C(object):
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
- range()
The range() function returns an iterable object (type is object), not a list type, so printing it will not print a list.
Function syntax:
range(stop)
range(start, stop[, step])
>>>range(5)
range(0, 5)
>>> for i in range(5):
... print(i)
...
0
1
2
3
4
>>> list(range(5))
[0, 1, 2, 3, 4]
>>> list(range(0))
[]
>>>
Cases with two or three arguments (second construction method):
>>>list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
>>> list(range(0, 10, 2))
[0, 2, 4, 6, 8]
>>> list(range(0, -10, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> list(range(1, 0))
[]
>>>
>>>
- repr()
Return a string containing a printable representation of an object.
>>>s = 'baidu'
>>> repr(s)
"'baidu'"
>>> dict = {'baidu': 'baidu.com', 'google': 'google.com'}
>>> repr(dict)
"{'google': 'google.com', 'baidu': 'baidu.com'}"
>>>
- reversed(seq)
Return a reverse iterator.
# String
seqString = 'Runoob'
print(list(reversed(seqString)))
# Tuple
seqTuple = ('R', 'u', 'n', 'o', 'o', 'b')
print(list(reversed(seqTuple)))
# range
seqRange = range(5, 9)
print(list(reversed(seqRange)))
# List
seqList = [1, 2, 4, 3, 5]
print(list(reversed(seqList)))
Output:
['b', 'o', 'o', 'n', 'u', 'R']
['b', 'o', 'o', 'n', 'u', 'R']
[8, 7, 6, 5]
[5, 3, 4, 2, 1]
- round(x[, n])
Return the rounded value of float x.
x- Numeric expression.
n- Number of decimal places to round x to, default is 0
print ("round(70.23456) : ", round(70.23456))
print ("round(56.659,1) : ", round(56.659,1))
print ("round(80.264, 2) : ", round(80.264, 2))
print ("round(100.000056, 3) : ", round(100.000056, 3))
print ("round(-100.000056, 3) : ", round(-100.000056, 3))
Output:
round(70.23456) : 70
round(56.659,1) : 56.7
round(80.264, 2) : 80.26
round(100.000056, 3) : 100.0
round(-100.000056, 3) : -100.0
- class set([iterable])
The set() function creates an unordered collection of unique elements. It can be used for relationship testing, removing duplicates, and computing intersections, differences, unions, etc.
>>> x = set('runoob')
>>> y = set('google')
>>> x, y
({'b', 'u', 'n', 'o', 'r'}, {'e', 'l', 'g', 'o'}) # Duplicates are removed
>>> x & y # Intersection
{'o'}
>>> x | y # Union
{'e', 'u', 'o', 'n', 'r', 'l', 'g', 'b'}
>>> x - y # Difference
{'b', 'u', 'n', 'r'}
>
- setattr(object, name, value)
The setattr() function corresponds to getattr(). It is used to set an attribute value; the attribute need not already exist.
Assign a value to an existing attribute:
>>>class A(object):
... bar = 1
...
>>> a = A()
>>> getattr(a, 'bar') # Get attribute bar value
1
>>> setattr(a, 'bar', 5) # Set attribute bar value
>>> a.bar
5
If the attribute does not exist, a new object attribute is created and assigned a value:
>>>class A():
... name = "runoob"
...
>>> a = A()
>>> setattr(a, "age", 28)
>>> print(a.age)
28
>>>
- class slice
- sorted(iterable, *, key=None, reverse=False)
Sort all iterable objects.
iterable– Iterable object.key– Mainly used for comparison. It takes only one argument; the function argument is taken from elements of the iterable object to specify which element to sort by.reverse– Sort order, reverse = True descending, reverse = False ascending (default).
Simplest usage of sorted:
>>>sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5] # Default is ascending
Using key for reverse sorting:
>>>example_list = [5, 0, 6, 1, 2, 7, 3, 4]
>>> result_list = sorted(example_list, key=lambda x: x*-1)
>>> print(result_list)
[7, 6, 5, 4, 3, 2, 1, 0]
>>>
For reverse sorting, also achievable by passing the third argument reverse=True:
>>>example_list = [5, 0, 6, 1, 2, 7, 3, 4]
>>> sorted(example_list, reverse=True)
[7, 6, 5, 4, 3, 2, 1, 0]
- @staticmethod
Transform a method into a static method.
A static method does not receive an implicit first argument. To declare a static method, use this syntax:
class C:
@staticmethod
def f(arg1, arg2, ...): ...
Static method calls can be made on the class (e.g. C.f()) or on an instance (e.g. C().f()).
- class str
Convert an object to a str object.
>>>s = 'w3cschool'
>>> str(s)
'W3Cschool'
>>> dict = {'w3cschool': 'w3cschool', 'google': 'google.com'};
>>> str(dict)
"{'google': 'google.com', 'w3cschool': 'w3cschool.cn'}"
>>>
- sum(iterable[, start])
>>>sum([0,1,2])
3
>>> sum((2, 3, 4), 1) # Sum of tuple then add 1
10
>>> sum([0,1,2,3,4], 2) # Sum of list then add 2
12
- super()
The super() function is used to call a method of the parent (super) class.
class A:
def add(self, x):
y = x+1
print(y)
class B(A):
def add(self, x):
super().add(x)
b = B()
b.add(2) # 3
- class tuple
Convert a list to a tuple.
>>>list1= ['Google', 'Taobao', 'Runoob', 'Baidu']
>>> tuple1=tuple(list1)
>>> tuple1
('Google', 'Taobao', 'Runoob', 'Baidu')
- type()
The type() function returns the type of an object if given only the first argument, or creates a new type object if given three arguments.
type(object)type(name, bases, dict)name– Name of the class.bases– Tuple of base classes.dict– Dictionary, namespace variables defined within the class.
Hint
Difference between isinstance() and type()
type() does not consider subclasses as a parent class type; inheritance is not considered.
isinstance() considers subclasses as a parent class type; inheritance is considered.
It is recommended to use isinstance() to check if two types are the same.
>>> type(1)
<type 'int'>
>>> type('runoob')
<type 'str'>
>>> type([2])
<type 'list'>
>>> type({0:'zero'})
<type 'dict'>
>>> x = 1
>>> type( x ) == int # Check if types are equal
True
# Three arguments
>>> class X(object):
... a = 1
...
>>> X = type('X', (object,), dict(a=1)) # Create a new type X
>>> X
<class '__main__.X'>
Difference between type() and isinstance():
class A:
pass
s
class B(A):
pass
isinstance(A(), A) # returns True
type(A()) == A # returns True
isinstance(B(), A) # returns True
type(B()) == A # returns False
- zip([iterable, ...])
The zip() function takes iterables as arguments, packages corresponding elements into tuples, and returns an object composed of these tuples. The advantage is significant memory savings.
We can use list() to output a list. If the iterables have different numbers of elements, the returned list length matches the shortest object. Using the * operator, tuples can be unpacked into lists.
>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b) # Returns an object
>>> zipped
<zip object at 0x103abc288>
>>> list(zipped) # list() converts to list
[(1, 4), (2, 5), (3, 6)]
>>> list(zip(a,c)) # Number of elements matches the shortest list
[(1, 4), (2, 5), (3, 6)]
>>> a1, a2 = zip(*zip(a,b)) # Opposite of zip, zip(*) can be understood as unpacking, returns 2D matrix form
>>> list(a1)
[1, 2, 3]
>>> list(a2)
[4, 5, 6]
>>>
Exceptions
- exception AssertionError
- exception AttributeError
- exception Exception
- exception ImportError
- exception IndexError
- exception KeyboardInterrupt
- exception KeyError
- exception MemoryError
- exception NameError
- exception NotImplementedError
- exception OSError
See CPython documentation:
OSError. MicroPython does not implement theerrnoattribute; instead, use the standard way to access exception arguments:exc.args[0].
- exception RuntimeError
- exception StopIteration
- exception SyntaxError
- exception SystemExit
See CPython documentation:
SystemExit.
- exception TypeError
See CPython documentation:
SystemExit.
- exception ValueError
- exception ZeroDivisionError