0

Hi lets say I have a list containing these string values:

food = ['apples', 'bananas', 'tofu', 'pork']

I'm tasked to write a function that takes the 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

My solution to this was:

def formatList(food):
    result = ""
    for idx in food: 
        result += idx + "," + " "
    return result

if I print this called function the result is:

print(formatList(food))
>> apples, bananas, tofu, pork,

The intended output is supposed to be:

print(formatList(food))
>> 'apples, bananas, tofu, and pork'

How can i fix this?

Mark Aaen
  • 15
  • 4

2 Answers2

2
food = ['apples', 'bananas', 'tofu', 'pork']

def concat(food):
    return ", ".join(food[:-1]) + " and " + food[-1]

print(concat(food))
## output 'apples, bananas, tofu and pork'
luckyCasualGuy
  • 641
  • 1
  • 5
  • 15
0

It can be done using the index of list instead of the content of list for the for loop:

def formatList(food):
    result = ""
    for i in range(len(food)):
        if i == len(food)-1:
            result += f"and {food[i]}"
        else:
            result += f"{food[i]}, "
    return result