Home > Back-end >  Can't get Python to print a range in a list without the last value
Can't get Python to print a range in a list without the last value

Time:08-11

new Python user here. I'm trying to get this code to run so that after the user inputs whatever they'd like on their list, it outputs with the values in the list, minus the last one. However, I can't get it to keep the last value out of the list; if I use the last line of code that I've commented out, it will tell me "TypeError: list indices must be integers or slices, not tuple

Can anyone point me in the right direction please?

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('You  want '  str(listToPrint)   ' and '   str(listToPrint[-1]))
#print('You  want '  str(listToPrint[0,-2])   ' and '   str(listToPrint[-1]))```


CodePudding user response:

It should be:

print('You  want '  str(listToPrint[0:-2])   ' and '   str(listToPrint[-1]))

CodePudding user response:

@wkl is right. listToPrint[:-1] gives you 0 to n-2 elements but str(listToPrint[:-1]) prints as list rather than string. Also you would want to do print(str(listToPrint[:-1]) 'and' str(listToPrint[-1])) to print all the elements in the list but again first n-1 items will be printed as list itself. You want following expression to correctly print out the elements in the list:

print("".join(listToPrint[:-1])   'and'   str(listToPrint[-1]))

CodePudding user response:

Long answer short: Use as below to suffice your requirement:

print("".join(listToPrint[:-1])   'and'   str(listToPrint[-1]))

Explanation: How lists range works is by using slicing operator : Example:

my_list = ['h','e','l','l','o']

# elements from index 1 to index 3
print(my_list[1:4])

Output

['e', 'l', 'l']

What you have used listToPrint[0,-2] is not the correct way.

CodePudding user response:

This error message "TypeError: list indices must be integers or slices, not tuple" is printed because you put a comma ',' between the brackets. In python the comma is a special char used to define tuples. For slices, you should use colon ':' as mentioned by wkl.

  • Related