I have been working on this question in particular. I'm a bit of a python beginner myself, having re-learnt functions just a few days back.
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. Be sure to test the case where an empty list [] is passed to your function.
My idea for this was to have my function run a for loop on the range of the number of elements of the list, add the elements of the list to a comma. If the element of the list happens to be the last element, 'and' and that specific element are added together.
Here is the code:
def listsmash(listu):
y = ''
for x in range(len(listu)):
if x == len(listu) -1 :
y+= 'and '+ str(listu[x])
else:
y+= str(listu[x]) + ','
return y
print(listsmash([1,345,34656,456456,456454564]))
Is this an efficient piece of code? Any way for me to make it more efficient than it already is?
'and'
. \$\endgroup\$