Main.ListsAsParameters History

Hide minor edits - Show changes to markup

February 16, 2010, at 08:44 AM MST by 71.196.160.210 -
Added lines 1-34:

(:source lang=python:)

"""Using lists as function parameters http://openbookproject.net/thinkcs/python/english2e/ch09.html#list-parameters """

def double_values(a_list) :

    for index, value in enumerate(a_list) :
        a_list[index] = 2 * value

things = [2, 5, 'Spam', 9.5] double_stuff(things) print things

  1. If a function modifies a list parameter, the caller sees the change.
  2. Let's write the same function such that it does not have the side effect
  3. of modifying its parameter

def double_values2(a_list):

    new_list = []
    for value in a_list:
        new_list += [2 * value]
    return new_list

things = [2, 5, 'Spam', 9.5] new_things = double_stuff2(things) print new_things print things

  1. which one is better?
  2. the second is less error prone

(:sourceend:)