most of these built-ins are available in both 2.x and 3.x.We specify explicitly when it is not the case
This is the first part of the series on python built-in functions. Here we will present the following built-ins: any() VS all(); instanceof() VS type(); filter(), map(), reduce(); print() VS format() and dir().
1. any() and all() any() >>> any([True])True
>>> any([True, True, True])
True
>>> any([True, True, False])
True
>>> l = [10, 20, 30]
>>> any([x>10 for x in l])
True
>>> any([x>50 for x in l])
False
>>> all() >>> all([True, True, True])
True
>>> all([True, True, False])
False
>>> all([x>10 for x in l])
False
>>> all([x>5 for x in l])
True
>>>
NB! An empty sequence returns True for all() and False for any()
>>> all([])True
>>> any([])
False
=================================
>>> any([0, 0.0, False, (), ‘0’]), all([1, 0.0001, True, (False,)])(True, True)
>>> any([0, 0.0, False, (), ”]), all([1, 0.0001, True, (False,), {}])(False, False)
=========================================
2. isinstance() and type() isinstance(object, class) >>> isinstance("linuxnix", str)True
>>> isinstance("linuxnix", object)
True
>>> isinstance(4.5, float)
True
>>> isinstance(4.5, int)
False
>>>
For a list of basic types in python see the official python documentation (https://docs.python.org/3.5/library/stdtypes.html)
type()be careful if you choose to use type() for type comparison.
>>> type(2)==intTrue
>>> type(2)=='int'
False
>>>
also be careful when using inheritance:
>>> class Kitty(object):... pass
...
>>> kit = Kitty()
>>> type(kit)
<class '__main__.Kitty'>
>>> type(kit)==Kitty
True
>>> type(kit)==object
False
>>>
instanceof() is a safer way of testing the type of an object. When in doubt, use instanceof().
3. print()Note: available in python 3.
In python 3 the print() function may take any number of arguments to be printed out (*objects) as well as a number of additional parameters, like sep and end , in a form of key-value arguments, which determine the basic output format:
print(*objects, sep='', end='\n', file=sys.stdout, flush=False) >>> print("London", "Bridge", "is", "falling", "down", sep='****', end='\nEND\n', file=sys.stdout, flush=False)London****Bridge****is****falling****down
END
>>> 5. dir() and help()
Without arguments, dir() returns the list of names in the current namespace. With an argument, returns a list of attributes and methods for that argument.
dir() Python 2.7.12 (default, Jul 1 2016, 15:12:24)[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> x="linux"
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'x']
>>> dir(x)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> x.upper()
'LINUX'
>>>
This comes in handy when you forgot some specific method (the exact form/spelling) or just want to see what methods are available for your object.
help()This function opens the built-in help system.
>>> help()Welcome to Python 2.7! This is the online help utility.
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/2.7/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".
To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics". Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".
help> keywords
Here is a list of the Python keywords. Enter any keyword to get more help.
and elif if print
as else import raise
assert except in return
break exec is try
class finally lambda while
continue for not with
def from or yield
del global pass
help>
If you want to obtain information about a specific function/module/object, you can provide a keyword as an argument to the help function.
>>> help(x)(opens a help page on the console)
Help on int object:class int(object)
| int(x=0) -> int or long
| int(x, base=10) -> int or long
|
| Convert a number or string to an integer or return 0 if no arguments
| are given. If x is floating point, the conversion truncates towards zero.
| If x is outside the integer range, the function returns a long instead.
...