Home > Enterprise >  How to get segregated x and y values in python args?
How to get segregated x and y values in python args?

Time:10-07

def makes_twenty(*args):
    for x,y in args:
        return x

makes_twenty(20,50,2)

I have written a function above. I gave three arguments and want to fetch two arguments in the variables x and y. however at the exact for loop line I get the following error and I am unable to understand why:

    for x,y in args:
TypeError: cannot unpack non-iterable int object

How can I fetch the values of args in the form of different variables using the for loop?

CodePudding user response:

for x,y in args: expects args to be a sequence of pairs, but args is a sequence of single integers (the tuple (20, 50, 2)); therefore, it can't unpack a single integer into two variables.

You could do the following, which will extract the first two arguments into x and y and any remaining arguments into z:

def makes_twenty(*args):
    x,y,*z = args
    return x

print(makes_twenty(20,50,2))

Output:

20

CodePudding user response:

You args value is a tuple with (20, 50, 2) If you iterate in your args variable the first element should be 20 the second 50 and the third 2

So when you try to iterate as for x,y in args: in the first iteration, the value is 20 but you are trying to unpack 2 variables when there is only one, so it throws an error.

You can do something like

def makes_twenty(*args):
    x,y, _ = args

print(makes_twenty(20,50,2))

You can see a _ this is usually using for unpack a variable that it will not be used.

  • Related