Positional Argument Confusion

I do NOT understand how this function works. Here is the solution given by Codecademy:

from os.path import join

path_segment_1 = “/Home/User”

path_segment_2 = “Codecademy/videos”

path_segment_3 = “cat_videos/surprised_cat.mp4”

join all three of the paths here!

print(join(path_segment_1, path_segment_2, path_segment_3)) # I understand this part

def myjoin(*args):

joined_string = args[0] #here is where they lost me. Why do we index the parameter???

for arg in args[1:]: #Again, why is this parameter being index? and, how would I even know to do this?

joined_string += '/' + arg # I understand this part

return joined_string

print(myjoin(path_segment_1, path_segment_2, path_segment_3))

Hi @dev6186850664.

If you’re passing an arbitraty argument list to a function with *args your will end up with a tuple called named args (the name can be changed but args is the standard) containing a sequence of all the arguments you passed to it. Try printing args inside the function.

In your example, args inside the function consists of three items. args[0] would be quivalent to path_segment_1, args[1] and [2] to path_segment_2 and _3 respectively as per the order they are passed to the function.
args == (path_segment_1, path_segment_2, path_segment_3)

These strings are then being concatenated with args[0] used as the first string and a loop used to add on each extra item sequentailly, starting at index 1 and stepping through to the end of the sequence [1:]. I’m guessing it’s written in this way to display how the arbitrary argument list is used rather than anything else.

1 Like

thank for that explanation! I am still confused as to why they used the index for joined_string = args[0] and for arg in args[1:]…I won’t focus much on trying to figure it out, right now. :slight_smile: