Home > Net >  How can I take a variable number of arguments into a function and use them as indices?
How can I take a variable number of arguments into a function and use them as indices?

Time:03-11

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?

CodePudding user response:

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".

CodePudding user response:

You can use operator.itemgetter to create a function that fetches items from an iterable (your string) with the given indexes, pass the indexes to the function by unpacking the passed args into positional arguments

from operator import itemgetter

def foo(my_string, *indices):
    return itemgetter(*indices)(my_string)

my_string = "tremendeous"
foo(my_string, 3, 7)  # ('m', 'e')
  • Related