Re: assignment in a for loop



"MackS" <mackstevenson@xxxxxxxxxxx> writes:

[MackS, please don't top-post.]

Suppose I want to do modify all arguments which are passed to a
function. Do I need to use a list comprehension such as

def f(arg1,arg2,arg3):

arg1,arg2,arg3 = [i+1 for i in (arg1,arg2,arg3)]
...

This would be awful when, eg, one adds an argument to the function
definition. It would require edition of the code at two different
locations.

If you anticipate increasing the number of values passed to the
function, and you're doing the same operation on all of them, why not
pass in a list::

>>> def add_one_to_each(nums):
... """ Makes a new list with each value incremented by one. """
...
... incremented_nums = [x+1 for x in nums]
... return incremented_nums
...
>>> foo = [3, 5, 8]
>>> bar = add_one_to_each(foo)
>>> bar
[4, 6, 9]

--
\ "Some mornings, it's just not worth chewing through the leather |
`\ straps." -- Emo Philips |
_o__) |
Ben Finney

.



Relevant Pages

  • Re: passing class by reference does not work??
    ... instance in my list comprehension in c, then the changes I made to ... sets in INSTANCE variable a the value computed on the RHS. ... You're not "passing the class", ... def getval: return A._val ...
    (comp.lang.python)
  • RE: c[:]()
    ... def b: print 'polly! ... for func in funcs: ... list comprehension or your "perlish" line noise is much more magic to ...
    (comp.lang.python)
  • Re: Newbie question about tuples and list comprehensions
    ... test each RGB band value per pixel, and set it to something else if it ... Why are you trying to do this with a list comprehension? ... Can't wait to try these suggestions out - cheers, idiolect ... def transform_image_getdata: ...
    (comp.lang.python)
  • Re: what is it, that I dont understand about python and lazy evaluation?
    ... I really started to ask myself if python really is lazy, but everything else I wrote in lazy style still worked. ... >> def test: ... As MRAB pointed out, the issue is not with evens, it's with the list comprehension. ...
    (comp.lang.python)
  • Re: Unsupported operand types in if/else list comprehension
    ... it is a string, and keep the item the same if it's anything else: ... I understand that if/else list comprehension should be generally: ... The parentheses around the conditional are unnecessary, but help with readability I think. ... *why* you are doing this in the def of QuoteIfString ...
    (comp.lang.python)