r/inventwithpython • • Aug 17 '16

my solution to Ch 4 practice comma code

Sharing this as I googled/reddited other answers with for loops built into them and couldn't wrap my head around that approach, and found an alternative way. I probably used too many variables but it was just easier to break it down that way for me.

import copy

spam = ['buttmonkeys','dsfdsfs','dsfsfsdfsfdfdsf','gggggg','dddddd','fff','ttt','123','789']

def thefunction(anylist):
	length=len(anylist)
	anylist.insert(length-1, 'and ') 
	lastitem= copy.copy(anylist[-1]) 
	stringedlist= ', '.join(anylist[:-1]) 
	lastlist= str(stringedlist)+str(lastitem)
	print(lastlist)
	
thefunction(spam)

Any helpful feedback is welcome.

2 Upvotes

1 comment sorted by

1

u/twowheelscat Aug 17 '16

You can do it like this:

spam = ['buttmonkeys','dsfdsfs','dsfsfsdfsfdfdsf','gggggg','dddddd','fff','ttt','123','789']
print(" and ".join(", ".join(spam).rsplit(", ", 1)))

or like this:

print(" and ".join([", ".join(spam[:-1]), spam[-1]]))