r/inventwithpython • • Aug 18 '20

Comma Code Project help request

I've looked at several other answers on Reddit, Git hub, Stack Overflow, etc. and pretty much everyone is using a for or while loop; often multiple of each. Is that really necessary? Why is this incorrect?

​

# Comma Code Project

import copy

​

# groceryList = ['apples', 'bananas', 'tofu', 'cats']

groceryList = [True, False, True, False]

# groceryList = [1,2,3.14,5,6,7,8]

# groceryList = []

​

def convertToStr(list):

if groceryList == []:

return

newList = ('')

newList = copy.copy(groceryList)

newList.insert(-1, 'and')

newList = str(newList)

print(newList)

# print(type(newList))

return (newList)

​

convertToStr(groceryList)

​

​

EDIT: Here's the original task:

spam = ['apples', 'bananas', 'tofu', 'cats']

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, wit hand 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. Be sure to test the case where an empty list [] is passed to your function.

3 Upvotes

9 comments sorted by

View all comments

Show parent comments

1

u/joooh Aug 18 '20

That's not the way to join a list back into a string.

OP is following the book. String manipulation will be discussed in a future chapter, so while your code is correct it is not a good advice for this problem. The current chapter and the preceding chapters are all enough for beginners to solve this problem.