Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #11780
| 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 <ppearson@nowhere.invalid> |
| 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> (permalink) |
| References | <a47fc507-4e45-4a1d-b133-10a6bd2095f3@c14g2000yqk.googlegroups.com> |
| 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 |
Show key headers only | View raw
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.
Back to comp.lang.python | Previous | Next — Previous in thread | Find similar | Unroll thread
lists and for loops Emily Anne Moravec <moravec@stolaf.edu> - 2011-08-17 20:08 -0700
Re: lists and for loops alex23 <wuwei23@gmail.com> - 2011-08-17 20:23 -0700
Re: lists and for loops Mark Niemczyk <prahamark@gmail.com> - 2011-08-18 05:22 -0700
Re: lists and for loops Tim Chase <python.list@tim.thechases.com> - 2011-08-18 07:45 -0500
Re: lists and for loops Peter Pearson <ppearson@nowhere.invalid> - 2011-08-18 16:43 +0000
csiph-web