user9502743
user9502743

Reputation: 11

using list comprehension not able to perform comparison how can i fix it

In list comprehension , using if in order to get the desired result but i am getting an error .I am not able to typecast the variable into integer from char.

Tried this code works well

list1=[int(x) for x in input().split()]
list2=[x for x in list1 if x<5 ]
print(list2)

But getting it done in one line does not

list1=[int(x) for x in input().split() if x<5]

or

list1=[x for int(x) in input().split() if x<5]

does not work

list1 should print all values less than 5.

Example User input: 2 5 6 8

print(list1)

should give result [2,5]

Upvotes: 1

Views: 77

Answers (2)

Sheldore
Sheldore

Reputation: 39072

The problem is that you are comparing a splitted string and an integer (5). Try converting to int type before checking with the if statement. Now both should work. Also, as pointed out by @prashantrana, given your output, it seems you need <=5 instead of <5

If you want a list of strings, then use

list1=[x for x in input().split() if int(x)<=5]

If you want a list of integers, then use

list1=[int(x) for x in input().split() if int(x)<=5]

Upvotes: 4

Bram Vanroy
Bram Vanroy

Reputation: 28505

The if is evaluated before the int conversion. So you are trying to compare 5 to a string. The expected fix can be found in the other answers. Here's an alternative.

Because you can.

s = '2 5 6 8'
i = list(filter(lambda i: i<=5, map(int, s.split())))

Upvotes: 1

Related Questions