3

I have a function that accepts multiple arguments. I can call it like:

i_take_strings('one', 'two', 'and_the_letter_C')

But suppose I want to determine the arguments dynamically, for example, by splitting a string. I tried:

s = 'one two and_the_letter_c'
    
i_take_strings(x for x in s.split())

but I get an error message. What is wrong, and how do I fix it?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
1Up
  • 994
  • 2
  • 12
  • 24
  • i_take_string(*tuple([x for x in s.split()])) would do, what you do is creating a generator, not a list. – mission.liao Aug 03 '15 at 04:42
  • 1
    @mission.liao code would work but could be simplified to `i_take_strings(*s.split())`. See [Pass list to function](https://stackoverflow.com/questions/3961007/passing-an-array-list-into-python) for more – LinkBerest Aug 03 '15 at 04:46
  • Python should not think you're retarded. You just tell it to pass an generator to the function - and python will do just that without questioning your mental health. – skyking Aug 03 '15 at 05:47

1 Answers1

7

s.split() already returns a list so you can pass it to your function as variable arguments by prepending * like follows:

i_take_strings(*s.split())
Community
  • 1
  • 1
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119