0

I need to add the word 'and' to the end of my list, as in

a, b, and c

So far I've got the commas sorted out. I've seen how to get at the last item in a list here

Getting the last element of a list in Python

but do not want to overwrite or replace the last item, just add a word in front of it. This is what I have so far:

listToPrint = []
while True:
    newWord = input('Enter a word to add to the list (press return to stop adding words) > ')
    if newWord == '':
        break
    else:
        listToPrint.append(newWord)
print('The list is: ' + ", ".join(listToPrint), end="")

As if its not too obvious, I'm fairly new to python, and this is being compiled in PyCharm.

Thanks in adv

Community
  • 1
  • 1
  • The simplest destructive way is to change the last item to `and X`, e.g. `listToPrint[-1] = 'and ' + listToPrint[-1]` just before your `print()`. – AChampion Dec 04 '16 at 21:46

1 Answers1

1

Use negative slicing for your list like this:

', '.join(listToPrint[:-1]) + ', and ' + listToPrint[-1]

With format() function:

'{}, and {}'.format(', '.join(listToPrint[:-1]), listToPrint[-1])

format() replaces the first {} with the value of ', '.join(listToPrint[:-1]) and the second {} with the value of listToPrint[-1]. for more details, check its documentation here format()

Output:

Enter a word to add to the list (press return to stop adding words) > 'Hello'
Enter a word to add to the list (press return to stop adding words) > 'SOF'
Enter a word to add to the list (press return to stop adding words) > 'Users'
# ... 
>>> print('{}, and {}'.format(', '.join(listToPrint[:-1]), listToPrint[-1]))
Hello, SOF, and Users
ettanany
  • 19,038
  • 9
  • 47
  • 63
  • That is perfect! I new I needed negative slicing, just unaware as to how to format it. So this formats it in the way I need regardless of the size of the list. How does this code work: '{}, and {}'.format ? – enjoyitwhileucan Dec 04 '16 at 22:08