[Tutor] Using a list as function argument?
Daniel Yoo
dyoo@hkn.eecs.berkeley.edu
Thu, 21 Dec 2000 02:47:39 -0800 (PST)
On Wed, 20 Dec 2000, Nate Bargmann wrote:
> I'm wanting to write a function that utilizes several arguments. As I
> intend to read the arguments out of a file, they are already in a list
> variable. I would like to pass this list to a function, do my
> processing and then return a list to the calling routine which I can
> use. I'm just getting starting in Python and I really didn't find an
> answer in the Python tutorial, the FAQ at python.org or in the TYP book.
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!