0

I'm doing an exercise from a python for beginners book. The project I'm stuck on is as follows: "Write a function that takes in a list of value as an argument and returns a string with all the items separated by comma and a space. Your function should be able to work with any list values passed to it"

Here is my code:

def passInList(spam):
       for x in range(len(spam)):
           z = spam[x] + ', ' 
           print(z,end= ' ')

spam=['apples', 'bananas', 'tofu', 'and cats']
passInList(spam)

Expected output is - 'apples, bananas, tofu, and cats'.

My output is- 'apples, bananas, tofu, and cats,'

The issue I'm having, is that I can't seems to get rid of the comma at the end of "cats".

Thanks for suggestions.

Dinesh Pundkar
  • 4,160
  • 1
  • 23
  • 37
AT_1965
  • 99
  • 1
  • 5
  • 11
  • Not directly related to your problem, but: the assignment says you should return a string, but your function doesn't return anything. – Kevin Aug 29 '16 at 20:13

5 Answers5

2

You could reduce your code to use join where you give it the separator and what list to join together.

def passInList(spam):
       print(', '.join(spam))

spam=['apples', 'bananas', 'tofu', 'and cats']
passInList(spam)
depperm
  • 10,606
  • 4
  • 43
  • 67
2

As people have posted here, join already exists. But if the exercise is meant to understand how to implement join, then here is one possibility:

def passInList(spam):
    s = spam[0]
    for word in spam[1:]:
        s += ', ' + word
    return s

That is you take the first word, then you concatenate each of the next words using a comma.

Another option to implement this is using functional programming, namely, in this case, the reduce function:

def passInList(spam):
    return functools.reduce(lambda x, y: x + ', ' + y, spam)

Whenever a scheme of aggregating things, like in the previous implementation's s += ... is used, reduce comes to mind.

Israel Unterman
  • 13,158
  • 4
  • 28
  • 35
0

Use join method:

spam=['apples', 'bananas', 'tofu', 'and cats']
print(', '.join(spam))
Mateusz Moneta
  • 1,500
  • 1
  • 10
  • 7
0

add a if statement to only add a comma if x is smaller than len(spam) -1, or better yet, use the str class' join function

Jules G.M.
  • 3,624
  • 1
  • 21
  • 35
0

You may use the join function which called with syntax 'str'.join(list). It joins all the elements in the list with str in between

>>> spam=['apples', 'bananas', 'tofu', 'and cats']
>>> my_string = ', '.join(spam)
>>> my_string
'apples, bananas, tofu, and cats'
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126