tags:

views:

121

answers:

1

I think 'unpack' might be the wrong vocabulary here - apologies because I'm sure this is a duplicate question.

My question is pretty simple: in a function that expects a list of items, how can I pass a Python list item without getting an error?

my_list = ['red', 'blue', 'orange']
function_that_needs_strings('red', 'blue', 'orange') # works!
function_that_needs_strings(my_list) # breaks!

Surely there must be a way to expand the list, and pass the function 'red','blue','orange' on the hoof?

+14  A: 
function_that_needs_strings(*my_list) # works!

You can read all about here.

THC4k
really spiffy :)
townsean
nice :) I would never have found this otherwise, so thanks :)
AP257
-1 Assuming that your `csvfile` is a `csv.writer` object, its `writerow` method has only one arg. `*args` in a function/method call is just a short way of writing `arg[0], arg[1], ...`. The function or method must be capable of handling the args that you supply. `*args` is not voodoo that overrides the funtion/method arg declaration. Your example "works" only when `len(my_list) == 1`. This is the worst case of Gadarene upvoting that I've seen for a while.
John Machin
@John Machin: You missed the point of the question. I just copied the function from the question's first revision - but I changed it just for you.
THC4k
@THC4k: I'm well aware of the point of the question. Where you copied parts of your answer from is irrelevant. My point is that the first sentence of your answer was ludicrously wrong.
John Machin
Then I hereby declare that you were wrong by "assuming that your csvfile is a csv.writer object" :P I don't get the point of this discussion anyways.
THC4k
yeah, @THC4k got the answer right - my bad for posting the wrong function in the question first time around...
AP257