Deleting numbers from a list

Question:

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:

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.

Asked By: Grindelwald

||

Answers:

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

Answered By: Seppe Willems

Use int in deleted_number

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=int(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)
Answered By: Summer
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.