0

I want to have an argument in a function that fills an array with multiple strings, so that i have

def Test(colors):
     colorarray = [colors]

which i can fill with

Test(red,blue)

but i always get either the takes 2 positional arguments but 3 were given error or the single strings do not get accepted (e.g. TurtleColor(Color[i]) tells me "bad color string: "red","blue")

i know i can pass the strings as seperate arguments, but i kind of want to avoid having that many different arguments.

Flying Thunder
  • 890
  • 2
  • 11
  • 37
  • You say `TurtleColor(Color[i])` throws a `bad color string: "red","blue"` error, but what _are_ `TurtleColor` and `Color` and `i`? – Aran-Fey May 07 '18 at 13:48
  • See [this question](https://stackoverflow.com/questions/16296643/convert-tuple-to-list-and-back) if you need to convert the `*args` tuple to a list. – Aran-Fey May 07 '18 at 13:49

1 Answers1

3

You need to read input arguments as a list

   def Test(*colors):
         colorarray = [*colors]
         print(colorarray)

    Test('red','blue')
anishtain4
  • 2,342
  • 2
  • 17
  • 21
  • That should work, what do i do if i have a second argument? e.g. def Test(*colors,size): and entering Test('red','blue',100) didnt work - told me it required a keyword-only argument: 'size' EDIT: Test('red','blue',size=100) does work. unsatisfying though, wonder if i can spare that "size=" with some syntax – Flying Thunder May 07 '18 at 13:51
  • @FlyingThunder: If the size is always there just change the order! `Test(size,*colors)` – anishtain4 May 07 '18 at 13:55
  • so the list has to come last, that shouldnt be a problem - i hope i dont stumble across a case where i have to input multiple lists then. thanks for quick advice – Flying Thunder May 07 '18 at 13:57
  • `list(colors)` would be more readable and more backwards compatible than `[*colors]`. – Aran-Fey May 07 '18 at 13:57
  • Aran is right, an alternative is to input colors as a single list argument that keeps your code cleaner (specially if you have multiple arguments). However instead of a list (which is mutable) I suggest to use tuples: `def Test(colors,size)`, and call it `Test(('red','blue'),100)` – anishtain4 May 07 '18 at 14:02
  • that seems to be working too and looks better, thanks for the tip! – Flying Thunder May 07 '18 at 14:06