a, b = <some expression>
interprets the result of the expression as a tuple with two values.__init__
and __del__
methods which have special significance in classes.x[key]
indexing operation for your class (just like you use it for lists and tuples), then all you have to do is implement the __getitem__()
method and your job is done. If you think about it, this is what Python does for the list
class itself!__init__(self, ...)
__del__(self)
__str__(self)
print
function or when str()
is used.__lt__(self, other)
__getitem__(self, key)
x[key]
indexing operation is used.__len__(self)
len()
function is used for the sequence object.lambda
statement is used to create new function objects. Essentially, the lambda
takes a parameter followed by a single expression. Lambda becomes the body of the function. The value of this expression is returned by the new function.more_lambda.py
):sort
method of a list
can take a key
parameter which determines how the list is sorted (usually we know only about ascending or descending order). In our case, we want to do a custom sort, and for that we need to write a function. Instead of writing a separate def
block for a function that will get used in only this one place, we use a lambda expression to create a new function.more_list_comprehension.py
):2*i
) when some condition is satisfied (if i > 2
). Note that the original list remains unmodified.*
or **
prefix respectively. This is useful when taking variable number of arguments in the function.*
prefix on the args
variable, all extra arguments passed to the function are stored in args
as a tuple. If a **
prefix had been used instead, the extra parameters would be considered to be key/value pairs of a dictionary.assert
statement is used to assert that something is true. For example, if you are very sure that you will have at least one element in a list you are using and want to check this, and raise an error if it is not true, then assert
statement is ideal in this situation. When the assert statement fails, an AssertionError
is raised. The pop()
method removes and returns the last item from the list.assert
statement should be used judiciously. Most of the time, it is better to catch exceptions, either handle the problem or display an error message to the user and then quit.retry
decorator for myself that I can just apply to any function and if any exception is thrown during a run, it is retried again, till a maximum of 5 times and with a delay between each retry. This is especially useful for situations where you are trying to make a network call to a remote computer: