{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# all() and any()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "all() and any() are built-in functions in Python that allow us to conveniently check for boolean matching in an iterable. all() will return True if all elements in an iterable are True. It is the same as this function code:\n", "\n", " def all(iterable):\n", " for element in iterable:\n", " if not element:\n", " return False\n", " return True\n", " \n", "any() will return True if any of the elements in the iterable are True. It is equivalent to the following function code:\n", "\n", " def any(iterable):\n", " for element in iterable:\n", " if element:\n", " return True\n", " return False\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's see a few examples of these functions. They should be fairly straightforward:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": true }, "outputs": [], "source": [ "lst = [True,True,False,True]" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "all(lst)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Returns False because not all elements are True." ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "any(lst)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Returns True because at least one of the elements in the list is True" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There you have it, you should have an understanding of how to use any() and all() in your code." ] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.10" } }, "nbformat": 4, "nbformat_minor": 0 }