Rajadurai M
Rajadurai M

Reputation: 191

How to pop an element, in list using user input?

cycles = ['hero','hercules']
user = input('enter pop cycle name \t')
cycles.pop(user)
print(user)

How do I remove an element based on a user input safely?

Upvotes: 1

Views: 1652

Answers (2)

AdamF
AdamF

Reputation: 2930

remove is the method to use! not pop. see python documentation.

cycles = ['hero','hercules']
while(True):
    user = input('enter pop cycle name \t')
    try:
        cycles.remove(user)
    except ValueError:
    print("Your input is not exist in the list! try again .. ")

Upvotes: 0

MercyDude
MercyDude

Reputation: 914

You should use remove() instead of pop(), like so

cycles = ['hero','hercules']
user = input('enter pop cycle name \t')
cycles.remove(user)
print(user)
print(cycles)
stored_var = user

note that if the element doesn't exist, it throws ValueError: list.remove(x): x not in list exception.

So, to safely remove an Item I'll suggest you to wrap the code with try and except

cycles = ['hero','hercules']
user = input('enter pop cycle name \t')

try:
  cycles.remove(user)
  print(user)
  print(cycles)
  stored_var = user

except:
  print("An exception occurred") 
  # handle it properly

Upvotes: 3

Related Questions