assignment in a for loop

Ben Finney bignose+hates-spam at benfinney.id.au
Wed May 17 02:05:49 EDT 2006


"MackS" <mackstevenson at hotmail.com> writes:

> Thank you for your reply.

A pleasure to help.

> > What's preventing the use of list comprehensions?
> >
> >     new_list = [x+1 for x in old_list]
> 
> Suppose I want to do anything as trivial as modify the values of the
> list members _and_ print their new values. List comprehensions must
> not contain statements, I think.

You're correct, but that's because you're creating a new list, not
modifying the existing one. The list comprehension can do anything you
like to generate each element, so long as it's an expression::

    >>> foo = [3, 5, 8]
    >>> print [x+1 for x in foo]
    [4, 6, 9]
    >>> print [x**2 for x in foo]
    [9, 25, 64]
    >>> print [str(x**2) for x in foo]
    ['9', '25', '64']
    >>> print [len(str(x**2)) for x in foo]
    [1, 2, 2]

If it's too complex to be readable in a single expression, make it a
function which returns a value, since calling a function is itself an
expression::

    >>> def get_result_of_complex_stuff(n):
    ...     quad = n**4
    ...     if len(str(quad)) % 2:
    ...         word = "spam"
    ...     else:
    ...         word = "eggs"
    ...     result = word.strip("s").title()
    ...     return result
    ...
    >>> foo = [3, 5, 8]
    >>> print [get_result_of_complex_stuff(x) for x in foo]
    ['Egg', 'Pam', 'Egg']

Once you have your new list being created by a list comprehension, do
what you like with it. If you want it to be stored, assigned back to
the original name, each value printed, or whatever you like, then do
so::

    >>> bar = [get_result_of_complex_stuff(x) for x in foo]
    >>> foo = bar
    >>> for x in foo:
    ...     print x,
    ...
    Egg Pam Egg

-- 
 \          "One time a cop pulled me over for running a stop sign. He |
  `\        said, 'Didn't you see the stop sign?' I said, 'Yeah, but I |
_o__)             don't believe everything I read.'"  -- Steven Wright |
Ben Finney




More information about the Python-list mailing list