[SOLVED] How can I take a variable number of arguments into a function and use them as indices?

Issue

Here is an example without a function:

my_string = "tremendeous"
my_tuples = (my_string[3], my_string[7])

Now if I want to generalize it, I’m lost as to how I can handle making the tuples variable in size?

What if the user wants 1 index, or maybe 3 indices or maybe 5 indices?

def doIt(my_string, *indices):
   
   my_tuples = (my_string[indices_1], my_string[indices_2] .... my_string[indices_n])

   return my_tuples

Someone could call: doIt("tremendeous", 3) or doIt("tremendeous", 3, 5) or doIt("tremendeous", 0, 3, 4, 4)

I know that I can use the "*" to take multiple arguments, but how can I feed a variable number of argument to my_tuples?

Solution

I believe this is what you are looking for:

In [10]: def doit(s, *indices):
    ...:     return tuple(s[i] for i in indices)

In [11]: doit("tremendous", 1, 3, 5, 7)
Out[11]: ('r', 'm', 'n', 'o')

See this SO question about "tuple comprehensions".

Answered By – Max

Answer Checked By – Pedro (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.