Home > OS >  I want to pop selected items on a number list
I want to pop selected items on a number list

Time:12-25

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.

CodePudding user response:

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

CodePudding user response:

The official Python documentation 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.

CodePudding user response:

You can use pop method:

my_list = []
for i in range(1, 21):
    my_list.append(i)

delete_numb = int(input("Delete a number: "))

for i, number in enumerate(my_list):
    if delete_numb == number:
        my_list.pop(i) 

CodePudding user response:

You can use just remove method:

mylist.remove(delete_number)

You can delete you want number.

CodePudding user response:

you can use list remove function

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


  • Related