I want to pop selected items on a number list

Question:

Whatever number the user types, I want this number to be deleted from the list

my_list = []
for i in range(1,21):
    my_list.append(i)
    
delete_numb= int(raw_input("Delete a number: ")

## in here code for delete delete_numb in my_list

I’m sure about this code. But I can’t next step for delete number.
I tried this:

del my_list[delete_numb]
my_list.pop(delete_numb)

These codes are work but not correct. I can’t understand what is theproblem.

Asked By: DarthWader

||

Answers:

You have to see index and element in array.

You have to do use remove for delete and element:

my_list = [1, 3, 5, 7, 9]
print "my_list"
  
my_list.remove(3)
my_list.remove(7)
    
print "my_list"

output:

[1, 3, 5, 7, 9]
[1, 5, 9]

If you use del or .pop you must give index number. For my_list = [1, 3, 5, 7, 9]

index 0: 1  
index 1: 3
index 2: 5
index 3: 7
index 4: 9
Answered By: mymiracl

This question has been answered here by the way: Is there a simple way to delete a list element by value?

The official Python documentation also provides useful info on lists: https://docs.python.org/3/tutorial/datastructures.html

There are 3 ways to remove an item on a list:

  1. Using the remove(x) method, which removes the first item from the list whose value is equal to x:
my_list = [i for i in range(1, 21)]
print('my_list before: ', my_list)

my_list.remove(int(input('Delete a number: ')))
print('my_list after: ', my_list)
  1. Using the del statement, which removes an item from a list given its index instead of its value (the pop() method will return a value, but the del statement will not return anything):
my_list = [i for i in range(1, 21)]
print('my_list before: ', my_list)

delete_numb = int(input("Delete a number: "))
del my_list[my_list.index(delete_numb)]
print('my_list after: ', my_list)
  1. Using the pop([i]) method, which removes the item at the given position in the list, and return it:
my_list = [i for i in range(1, 21)]
print('my_list before: ', my_list)

delete_numb = int(input('Delete a number: '))
my_list.pop(my_list.index(delete_numb))
print('my_list after: ', my_list)

index(x) method returns zero-based index in the list of the first item whose value is equal to x.

Answered By: コリン

You can use remove function

my_list = [i for i in range(1,21)]   
delete_numb= int(raw_input("Delete a number: ")
my_list.remove(delete_numb)
Answered By: tomerar

You can use just remove method:

mylist.remove(delete_number)

You can delete you want number.

Answered By: Mahmut Uslu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.