assignment in a for loop
Ben Finney
bignose+hates-spam at benfinney.id.au
Wed May 17 01:11:51 EDT 2006
"MackS" <mackstevenson at hotmail.com> 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
More information about the Python-list
mailing list