+ 1

Help explain how to write this Function

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, 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.

31st Aug 2019, 4:24 PM
hartechworld
hartechworld - avatar
12 Respostas
+ 2
Why don't you give a try??
31st Aug 2019, 4:42 PM
Мг. ĐšĐœĐ°ĐżđŸŒ 
Мг. ĐšĐœĐ°ĐżđŸŒ  - avatar
+ 1
not just merely printing out the values
31st Aug 2019, 5:18 PM
hartechworld
hartechworld - avatar
31st Aug 2019, 5:25 PM
Мг. ĐšĐœĐ°ĐżđŸŒ 
Мг. ĐšĐœĐ°ĐżđŸŒ  - avatar
+ 1
Thank you Sami Khan
31st Aug 2019, 5:36 PM
hartechworld
hartechworld - avatar
0
spam = ['apples','bananas','tofu','cats'] def listFunction(listValue): listValue.insert(3, 'and') return listValue print(listFunction(spam)) OUTPUT: ['apples', 'bananas', 'tofu', 'and', 'cats'] I don’t think this is right because if the size of the list changes, this funcation will not be effective. commas are not added. Sami Khan
31st Aug 2019, 5:03 PM
hartechworld
hartechworld - avatar
0
But u can get the length of the list right? Just subtract one from it listValue.insert(len(spam)-1, 'and')
31st Aug 2019, 5:12 PM
Мг. ĐšĐœĐ°ĐżđŸŒ 
Мг. ĐšĐœĐ°ĐżđŸŒ  - avatar
0
thanks that works now, but how do I put commas in between the list values?
31st Aug 2019, 5:16 PM
hartechworld
hartechworld - avatar
0
Cbr✔[ ZeroCharisma ] its not a homework, reading the book: Automate the boring stuff with Python. thats an excercise, thank you
31st Aug 2019, 6:13 PM
hartechworld
hartechworld - avatar
0
This is my result : def a(spam): for i in range(len(spam)-1): if spam[0] in spam[i]: print("'",end='') c=(spam[i]+',') print(c,end='') if spam[-1] not in spam[i]: print('and '+spam[-1]+"'") a(['tĂĄo', 'chuối', 'đáș­u phỄ', 'mĂšo'])
9th Mar 2020, 7:02 AM
Sau Truong
Sau Truong - avatar
0
def lol(a): lastWord = a[len(a)-1] + '.' del a[len(a)-1] a.append('end ' + lastWord) L=0 while L<=len(a)-2: print(a[L],end=', ') L=L+1 else: print(a[len(a)-1]) spam = ['apples','bat','tofu','cats'] lol(spam)
13th Apr 2020, 6:54 PM
эроĐș ĐšĐ°Ń€Ń‚ĐŒĐ°Đœ
эроĐș ĐšĐ°Ń€Ń‚ĐŒĐ°Đœ - avatar
0
spam = ['apples','bananas','tofu','cats','apples','bananas','tofu','cats'] def listFunction(listValue): i = 0 while i < len(listValue)-1: print (listValue[i]+',', end='') i=i+1 print('and '+listValue[-1]) listFunction(spam)
26th Jan 2023, 12:21 PM
ning