1

I just want to understand why we use *args when the same work can be done by list when we pass it as a argument. In which scenarios do we really need *args, where list as a argument will fail to do that operation.

list =[1,2,3,4,5,6,7]
def method1(args):
    for i in args:
        print(i*2)
method1(list)
list =[1,2,3,4,5,6,7]
def method1(*args):
    for i in args:
        print(i*2)
method1(*list)

I didn't find any differences. Please correct me if i am wrong.

Joris C.
  • 5,721
  • 3
  • 12
  • 27
  • 1
    yep, your examples are flawed, and don't quite showcase how you can pass a variable number of arguments in `*args`. (Your first example is only passing 1 item. that being a list.) – Paritosh Singh Aug 18 '19 at 09:30
  • 2
    @ParitoshSingh In this case the OP know what they are (and also argument list unpacking), just don't know when they're useful. I think it's on topic to ask for example usage of a feature. – user202729 Aug 18 '19 at 09:55
  • Aye, which i think the answer on the dupe target adequately addresses. But if the OP disagrees they can say so. – Paritosh Singh Aug 18 '19 at 10:26

2 Answers2

2
def method1(args):
    print(args)
method1(5) it will print 5
method1() method1() missing 1 required positional argument: 'args'
method1(2,6) TypeError: method1() takes 1 positional argument but 2 were given

To Avoid this situation we use

def method1(*args):
    print(args)
method1(1, 2, '3')
(1, 2, '3') print this

So *args is useful when we don’t know in advance how many arguments we need to pass in.

AnkushRasgon
  • 782
  • 1
  • 6
  • 14
0

The difference is that you can pass any number of arguments in the second case where it will throw error in the first case.

Case 1:

lst = [1,2,3,4,5,6,7]
a = 1
b = 2

def method1(args):
    for i in args:
        print(i*2)

method1(lst, a, b)

...fails with 'TypeError: method1() takes 1 positional argument but 3 were given'.

Case 2 (i):

lst = [1,2,3,4,5,6,7]
a = 1

def method1(*args):
    for i in args:
        print(i*2)

method1(lst, a)

...works.

Case 2 (ii):

lst = [1,2,3,4,5,6,7]
a = 1
b = 2

def method1(*args):
    for i in args:
        print(i*2)

method1(lst, a, b)

...works and so on, you can pass any number of arguments.

Austin
  • 25,759
  • 4
  • 25
  • 48