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.

2
  • You say TurtleColor(Color[i]) throws a bad color string: "red","blue" error, but what are TurtleColor and Color and i? Commented May 7, 2018 at 13:48
  • See this question if you need to convert the *args tuple to a list. Commented May 7, 2018 at 13:49

1 Answer 1

3

You need to read input arguments as a list

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

    Test('red','blue')
Sign up to request clarification or add additional context in comments.

6 Comments

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
@FlyingThunder: If the size is always there just change the order! Test(size,*colors)
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
list(colors) would be more readable and more backwards compatible than [*colors].
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)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.