Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Deleting numbers from a list

The program should generate 10 random numbers in the interval
[1;3], store them in a list, and print the contents of the list
on the screen! The user should be able to enter a number in the
interval [1;3], and the program should delete all occurrences
of this number from the list, and then print the modified list
on the screen!

I tried to run the following program with two methods, but they do not produce the final list that I wanted.

First try:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import random

random_list=[]
number=0
deleted_number=0
final_list=[]

for i in range(10):
    number=random.randint(1,3)
    random_list.append(number)
print(random_list)
deleted_number=input('Give a number from 1 to 3, that you want to delete from the list.')
final_list = list(set(random_list) - set(deleted_number))
print('The new list without the deleted values:')
print(final_list)

Second try:

import random
random_list=[]
number=0
deleted_number=0
final_list=[]

for i in range(10):
    number=random.randint(1,3)
    random_list.append(number)
print(random_list)
deleted_number=input('Give a number from 1 to 3, that you want to delete from the list.')
final_list = [item for item in random_list if item != deleted_number]
print('The new list without the deleted values:')
print(final_list)

Thank you for your help in advance.

>Solution :

You need to convert the user input from a string to an int like this:

deleted_number = int(input('Give a number from 1 to 3, that you want to delete from the list: '))

and the line

final_list = [item for item in random_list if item != deleted_number]

is correct on your second try

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading