Valerius Bokštas
Valerius Bokštas

Reputation: 33

Remove values from list leaving only unique values

So, basically what I need is to write a program where user types a list of integers, stores them in another list with values only 1-100 and displays the resulting list. My issue there is that my program deletes not all of the values I need to, and I need all of the values be deleted from list outside the range of 1-100. Theres no excuse for my title, but I'm not sure how to call this problem.

def inputnumber():
    numbers = input('Enter number(s): ').split(',')
    return [int(i) for i in numbers]

x = inputnumber()
for i in x:
    if i > 100 or i < 1:
        x.remove(i)
y = list(set(x))
print(y)

I mean when I type list of numbers [5, -10, 22, 133, 16, 0, 103, 100, -60], I get a result of [16, 100, 5, 22, 103] - 103 should be out of there. When I type list [5, -10, -15, -20, -60, 103, 108, 10], I get [-15, 10, -60, 5, 108] - and I should get [10, 5] only. Maybe I should look for some other function, not ''remove'' or is there a way to delete all of them?

Upvotes: 1

Views: 99

Answers (5)

Valerius Bokštas
Valerius Bokštas

Reputation: 33

After couple of hours reading and trying I found out that this program can be made without using set as well. Like this, and it gives proper sequence:

def inputnumber():
    numbers = input('Enter number(s): ').split(',')
    return [int(i) for i in numbers]

x = inputnumber()
y = [i for i in x if i>=1 and i<=100]
print(y)

Upvotes: 0

jamylak
jamylak

Reputation: 133554

You are mutating the list x as you iterate over it by removing items in the for loop. This causes you to skip skip over elements in the list such as 103. You can iterate over a copy instead to fix this problem

for i in list(x): # iterates over a (shallow) copy 

However the solution

y = list(set(e for e in x if e in range(1, 101)))

By @ReutSharabani

is probably the best way to approach this problem.

Upvotes: 0

rchang
rchang

Reputation: 5236

Python has a built-in function called filter that may help (edited to include @ReutSharabani's shorthand suggestion for the lambda definition).

x = inputnumber()
x = filter(lambda i: 1 <= i <=100, x)
y = list(set(x))
print(y)

Upvotes: 2

Reut Sharabani
Reut Sharabani

Reputation: 31339

Change :

y = list(set(x))

To:

y = list(set(filter(lambda e: 1 <= e <= 100, x)))

This uses filter to filter x before constructing the set

or:

y = list(set([e for e in x if e in range(1, 101)]))

This uses list comprehension to filter the values you're not interested in and constructs the set using those values.

Upvotes: 4

kevr91
kevr91

Reputation: 1

You can use a list comprehension.

x = [i for i in x if i > 1 and i < 100]

Upvotes: 0

Related Questions