4

Lets say I have a function that takes string arguments. But I want to dynamically generate them. There does not seem to be a way to plug this in easily. How is this done? See my example here

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

s = 'one two and_the_letter_c'

i_take_strings(x for x in s.split()) #python thinks I'm retarded with this attempt
1Up
  • 946
  • 2
  • 10
  • 22
  • 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
  • 45,449
  • 17
  • 80
  • 115