Doubt def function with tuple mode input

Asked

Viewed 91 times

1

Good person I have the following code:

    def tuplas(x):

        return x[::2]

tuplas(('Hello', 'World', 'estamos', 'vivos'))

This code will work perfectly, but if I remove the parentheses of my tuple, obviously the python will give error:

TypeError: tuplas() takes 1 positional argument but 4 were given

Obviously because there is I have defined only one argument in the function, it is actually clear I would have to have inserted an argument for each item of the tuple. I who inserting the data in string mode "Hello World we are alive" is giving a split I will succeed but the output will be as string and not a tuple.

The doubt is possible I insert my data in the form of tuple not putting the parentheses ex: 'Hello', 'World', 'we are', 'alive' with only one argument in the function def tupla(x), not asking me to put the other arguments is this output is in the form of tuple same.

the function would be as follows:

    def tuplas(x):

        return x[::2]

tuplas('Hello', 'World', 'estamos', 'vivos') # desse modo da error

Or there would be no way, I would have to put the parentheses for python to recognize this as tuple.

I hope I was clear.

1 answer

3


There is a special syntax that allows you to receive a variable number of information in a function:

>>> def tuplas(*args):
...     return args[::2]
... 
>>> tuplas('Hello', 'World', 'estamos', 'vivos')
('Hello', 'estamos')
  • Perfect @Masrcelo-Theodoro functional 100%

Browser other questions tagged

You are not signed in. Login or sign up in order to post.