Home > Back-end >  How do I add an element to right before the last element?
How do I add an element to right before the last element?

Time:06-16

I can't figure out how to index list.insert if the prompt allows the user to add multiple items to the list. I need to add "and" right before the last item of what ever is listed.

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(listToPrint)

CodePudding user response:

As @christiandean suggested in the comments, this is what you're after:

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)

listToPrint.insert(len(listToPrint)-1, "and")

print(listToPrint)

However, that fails if there's no words entered, so this is safer:

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)

if len(listToPrint) > 1:
    listToPrint.insert(len(listToPrint)-1, "and")

print(listToPrint)

Output:

Enter a word to add to the list (press return to stop adding words) > this
Enter a word to add to the list (press return to stop adding words) > that
Enter a word to add to the list (press return to stop adding words) > more
Enter a word to add to the list (press return to stop adding words) > 
['this', 'that', 'and', 'more']

CodePudding user response:

I hope I’m understanding the question correctly. If not, please forgive me. So,[-1] would index the last element of the sequence, I believe. Therefore [-2] would indicate the next to last element.

CodePudding user response:

In essence, this should done using:

listLen = len(listToPrint)
if listLen > 1:
    listToPrint.insert(listLen - 1, "and")
  • Related