Write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item. For example, passing the previous spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list value passed to it.

Respuesta :

Answer:

The function in Python is as follows:

def myfunction(mylist):

    listitems = ""

    for i in range(len(mylist)):

         if (i < len(mylist)-1):

              listitems = listitems + mylist[i] + ", "

         else:

              listitems = listitems + "and "+mylist[i]

   

    return listitems

Explanation:

This defines the function

def myfunction(mylist):

This initializes an empty string which in the long run, will be used to hold all strings in the list

    listitems = ""

This iterates through the list

    for i in range(len(mylist)):

For list items other than the last item, this separates them with comma (,)

         if (i < len(mylist)-1):

              listitems = listitems + mylist[i] + ", "

For the last item, this separates with and

         else:

              listitems = listitems + "and "+mylist[i]

   

This returns the required string

    return listitems

ACCESS MORE