Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!news.albasani.net!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Peter Pearson Newsgroups: comp.lang.python Subject: Re: lists and for loops Date: 18 Aug 2011 16:43:20 GMT Lines: 26 Message-ID: <9b4tp8FdrgU1@mid.individual.net> References: X-Trace: individual.net qNcirKAQSE0EtmawA5z+jQ2jvaDO6790HG9Qu4sCYAt1L6NFXy Cancel-Lock: sha1:AJoJrjT0TfQokrvmHHttPzAxbFI= User-Agent: slrn/pre1.0.0-16 (Linux) Xref: x330-a1.tempe.blueboxinc.net comp.lang.python:11780 On Wed, 17 Aug 2011 20:08:23 -0700 (PDT), Emily Anne Moravec wrote: > I want to add 5 to each element of a list by using a for loop. > > Why doesn't this work? > > numbers = [1, 2, 3, 4, 5] > for n in numbers: > n = n + 5 > print numbers Because integers are immutable. You cannot turn 1 into 6. Contrast this behavior with lists, which *are* mutable: >>> numbers = [[1],[2],[3],[4],[5]] >>> for n in numbers: ... n[0]= n[0] + 5 ... >>> numbers [[6], [7], [8], [9], [10]] For practical purposes, I'm sure you'll find other responders' excellent posts to be of more immediate use, but keeping mutability in mind helps. -- To email me, substitute nowhere->spamcop, invalid->net.