[Tutor] Using a list as function argument?

D-Man dsh8290@rit.edu
Thu, 21 Dec 2000 08:54:06 -0500


On Thu, Dec 21, 2000 at 02:47:39AM -0800, Daniel Yoo wrote:
> Let's try to write a function that, given a list of numbers, returns back
> a list of those numbers doubled.  Here's a small interpreter session:
> 
> ###
> >>> def doubleNumbers(numbers):
> ...     results = []  # we'll collect our results in here 
> ...     for x in numbers:
> ...         results.append(x + x)
> ...     return results
> ... 
> >>> doubleNumbers([1, 2, 3, 4, 5])
> [2, 4, 6, 8, 10]
> >>> doubleNumbers("testing")
> ['tt', 'ee', 'ss', 'tt', 'ii', 'nn', 'gg']
> ###
> 
> So our doubleNumbers function can work on lists of numbers.  The
> surprising thing is that it works on any kind of "sequence" --- anything
> that we can do a for-loop around.  Just wanted to play around with it...
> *grin*
> 
> So basically, you can make an empty list, and collect your results into it
> by using its append() function.  This is the skeleton that I use when I
> want to process lists.  Hope this helps!
> 

Depending on your purpose in writing this, you could do:

for i in range( len( numbers ) ) :
	numbers[i] += numbers[i] # this only works in Python 2.0
	# numbers[i] = numbers[i] + numbers[i] # this will work in older pythons


This sort of thing can be dangerous though since the argument is
modified.  It is generally considered cleaner to return the result
instead like in Daniel's example.

-D