0

Code:

def op(*ar):
  for i in ar:
    print(i)

arg=['yel','5',6]
op(arg)

Output: ['yel','5',6]

Code:

def op(ar):
  for i in ar:
    print(i)

arg=['yel','5',6]
op(arg)

Output:

yel
\n5
\n6(This output is understood)
ggorlen
  • 44,755
  • 7
  • 76
  • 106
Nitin
  • 1
  • 1
    In the first one, you've given `*args` which is variable positional arguments packed as a tuple. You can print it in the function to see what it is. `ar[0]` is your list, the only parameter you passed in, so it gets printed. Use `for i in ar[0]:` if you want to get the same output as the second example. This means, iterate over the first of the variable arguments provided to the func. – ggorlen Jun 07 '20 at 05:56
  • Because in first code, the whole list is passed as one argument. If you try `op(*arg)` in the last line of your first code, you would get the same output as second code. – monte Jun 07 '20 at 06:02

1 Answers1

0

This is easy....You see *args takes all the arguments and passes it onto the function as a tuple.

So, when you write def op(*args): you are actually passing a tuple containing the list ['yel', '5', '6']. The argument that is passed looks actually like this: (['yel', '5', '6'])

Now when you iterate through the tuple are inside the function, i there is each element of tuple, i.e, i in this case is the whole list ['yel', '5', '6'].

This is why you are getting a list when you print ar.

In contrary, in the second case the argument is passed as list and hence you can access each element when you iterate through it.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Sobhan Bose
  • 114
  • 9