{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "#enumerate()\n", "\n", "In this lecture we will learn about an extremely useful built-in function: enumerate(). Enumerate allows you to keep a count as you iterate through an object. It does this by returning a tuple in the form (count,element). The function itself is equivalent to:\n", "\n", " def enumerate(sequence, start=0):\n", " n = start\n", " for elem in sequence:\n", " yield n, elem\n", " n += 1\n", "\n", "##Example" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "a\n", "1\n", "b\n", "2\n", "c\n" ] } ], "source": [ "lst = ['a','b','c']\n", "\n", "for number,item in enumerate(lst):\n", " print number\n", " print item" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "enumerate() becomes particularly useful when you have a case where you need to have some sort of tracker. For example:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "a\n", "b\n" ] } ], "source": [ "for count,item in enumerate(lst):\n", " if count >= 2:\n", " break\n", " else:\n", " print item" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Great! You should now have a good understanding of enumerate and its potential use cases." ] } ], "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.11" } }, "nbformat": 4, "nbformat_minor": 0 }