Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #11746

Re: lists and for loops

Date 2011-08-18 07:45 -0500
From Tim Chase <python.list@tim.thechases.com>
Subject Re: lists and for loops
References <a47fc507-4e45-4a1d-b133-10a6bd2095f3@c14g2000yqk.googlegroups.com> <b599dd9d-0533-44ef-9bb5-8ce2db4760e8@m5g2000prh.googlegroups.com> <8307c651-e4c1-4d28-9f2a-bf0513f21eb8@glegroupsg2000goo.googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.154.1313671526.27778.python-list@python.org> (permalink)

Show all headers | View raw


On 08/18/2011 07:22 AM, Mark Niemczyk wrote:
> Or, using list comprehension.
>
>>>> numbers = [1, 2, 3, 4, 5]
>>>> numbers = [n + 5 for n in numbers]
>>>> numbers
> [6, 7, 8, 9, 10]

Or, if you want it in-place:

   numbers[:] = [n+5 for n in numbers]

which makes a difference if you have another reference to numbers:

 >>> numbers = [1,2,3,4,5]
 >>> digits = numbers
 >>> numbers = [n+5 for n in numbers]
 >>> numbers, digits
([6, 7, 8, 9, 10], [1, 2, 3, 4, 5])
 >>> numbers = [1,2,3,4,5]
 >>> digits = numbers
 >>> numbers[:] = [n+5 for n in numbers]
 >>> numbers, digits
([6, 7, 8, 9, 10], [6, 7, 8, 9, 10])

-tkc


Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


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