{ "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": {}, "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": 2, "metadata": {}, "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": [ "enumerate() takes an optional \"start\" argument to override the default value of zero:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[(3, 'March'), (4, 'April'), (5, 'May'), (6, 'June')]" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "months = ['March','April','May','June']\n", "\n", "list(enumerate(months,start=3))" ] }, { "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 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.2" } }, "nbformat": 4, "nbformat_minor": 1 }