{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "### Swapping variable values\n", "\n", "Suppose" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "a, b = 42, 43" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We've see the following options for swapping their values. One is using multiple assignment:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": true }, "outputs": [], "source": [ "a, b = b, a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Another is using a temporary variable:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": true }, "outputs": [], "source": [ "temp = b\n", "b = a\n", "a = temp" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here is how we can swap the values of two integer variables without using either of those tricks:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": true }, "outputs": [], "source": [ "a, b = 42, 43\n", "\n", "#Suppose a == a', b = b'. That is, a' is the \"old\" value of a, and b' is the \"old\" value of b\n", "\n", "a = a + b #a == a' + b', b == b'\n", "b = a - b #a == a' + b', b == a'\n", "a = a - b #a == b', b == a'" ] } ], "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.4.3" } }, "nbformat": 4, "nbformat_minor": 0 }