AishwaryaKulkarni AishwaryaKulkarni - 1 month ago 8
Python Question

Getting wrong length for a list in if condition in python

I have python list

fin_list
as follows:

fin_list = [
['1', '15'],
['3', '5', '1'],
['140', '147', '141'],
['133', '137', '134'],
['10', '12', '11'],
['12', '16', '15'],
['9', '10', '112576569'],
['8', '9', '10'],
['7', '8'],
['15', '16', '9', '133889916'],
['1', '3', '74228172'],
['3', '5', '1'],
['5', '6'],
]


and I want to remove all the lists having large numbers like 112576569, 133889916 and 74228172. Hence I am putting a condition in my code as:

if(all(i<=1000 for i in fin_list)):
print fin_list


However when I put this condition , I get no output but when I put the condition,
i>=1000
, all the lists show up in the output.

Answer

You don't have numbers. You have strings. Strings are ordered lexicographically, and actual numbers (like 1000) are always ordered before other types when using comparisons in Python 2.

So '133889916' <= 1000 is always going to be false, because numbers are sorted before strings:

>>> '133889916' <= 1000
False
>>> '1000' <= 1000
False

Convert your strings to integers first:

if all(int(i) <= 1000 for i in fin_list):