Saloni Mude
Saloni Mude

Reputation: 39

Adding user input to a list , then deleting it if the input exists in the list or appending it if it does not

So I want to ask a user to enter a letter for a pre-made list. If that letter already exists in that list , I want to have that letter deleted , if it does not exists in the list , I want it appended to the list. This is the code I'm using right now :

list1= ['a','b','c','d','e']
letter=input("please input a letter ")
for letter in list1:
    if letter in list1:
         del list1[letter]
         print(list1)
    else:
         print(list1.append(letter)

It gives the type-error that list indices must be integers not string. How do I go about this ?

Upvotes: 1

Views: 2063

Answers (3)

Ahasanul Haque
Ahasanul Haque

Reputation: 11144

Pretty simple it is. Remove the value if it exists in the list, append if not.

list1= ['a','b','c','d','e']
letter=raw_input("please input a letter ")
list1.remove(letter) if letter in list1 else list1.append(letter)

Upvotes: 1

Martin Evans
Martin Evans

Reputation: 46779

If the letter is in list1, you can use remove to delete it, and append can be used to add the new letter to the end of the list. The following script lets you see it working:

list1 = ['a','b','c','d','e']

while True:
    print('Current list:', list1)
    letter = input("Please input a letter: ")

    if letter in list1:
        list1.remove(letter)
    else:
        list1.append(letter)

For example:

Current list: ['a', 'b', 'c', 'd', 'e']
Please input a letter: f
Current list: ['a', 'b', 'c', 'd', 'e', 'f']
Please input a letter: b
Current list: ['a', 'c', 'd', 'e', 'f']
Please input a letter: a
Current list: ['c', 'd', 'e', 'f']

Upvotes: 0

Vikas Ojha
Vikas Ojha

Reputation: 6950

You will need to pop the letter at the index. Also there is no need for the for loop. Edited answer to incorporate @lukasz comment.

list1= ['a','b','c','d','e']
letter=input("please input a letter ")
if letter in list1:
    list1.remove(letter)
else:
    print(list1.append(letter))

Upvotes: 3

Related Questions