3

I have a list of integers which I have extracted from a string of text, so when I print the list (which I have called test) I get:

['135', '2256', '1984', '3985', '1991', '1023', '1999']

and I want to print or make a new list containing only numbers within a certain range, e.g. between 1000-2000. I tried the following, but it still returns all of the items in my original list.

for i in test:
    if i>1000:
        print i
    elif i<2000:
        print i

And I can't work out why it would still be printing numbers below 1000 or above 2000.

5
  • don't compare strings with integers... Commented Oct 12, 2018 at 11:33
  • 1
    hint #2: 1 is less than 2000, 1000 is more than 1000 Commented Oct 12, 2018 at 11:33
  • btw TypeError: unorderable types: int() < str() in python 3, isn't this python 2? Commented Oct 12, 2018 at 11:34
  • of course it is python 2: the print statements!!! Commented Oct 12, 2018 at 11:40
  • Sorry yes, it is python 2 apologies. Also I didn't notice that it was a list of strings instead of integers - problem solved! Commented Oct 12, 2018 at 12:04

6 Answers 6

7

First convert your list of strings to a list of ints:

ints_list = [int(x) for x in test]

Then you can filter this list however you would like. We can do this with a list comprehension like the above line. Notice the and that makes it so that the number has to meet both conditions to be in the list.

filtered_list = [x for x in ints_list if x > 1000 and x < 2000]
Sign up to request clarification or add additional context in comments.

7 Comments

I believe you mean x < 2000
Thanks @NinadGaikwad
Ah thanks, I didn't realise I had strings instead of integers, that makes sense. However when I try to run the first line in your comment I get an error: " TypeError: 'str' object is not callable". Do you maybe know what the cause could be? Thanks again!
You don't have a variable named str do you? That might cause that since that is supposed to be reserved as a Python keyword.
Try this: [int(x) for x in ['135', '2256', '1984', '3985', '1991', '1023', '1999']] Tested in Python 3.6 and Python 2.7
|
1

It's ambiguous whether you are using Python 2 or 3. You tagged Python 3, but in this case you should be getting a TypeError instead of semantically incorrect output. This answer works for both versions of Python.

test is a list of strings, but you want to do integer comparisons.

Build a list of integers first, then apply your algorithm.

>>> test = ['135', '2256', '1984', '3985', '1991', '1023', '1999']
>>> test_ints = [int(x) for x in test] # or test_ints = map(int, test)
>>> for i in test_ints:
...     if i > 1000:
...         print(i)
...     elif i < 2000:
...         print(i)
... 
135
2256
1984
3985
1991
1023
1999

Now the code runs, but still has bugs. Note how 135 is falsely printed, because it is not greater than 1000 but smaller than 2000.

A bug free version could look like this:

>>> for i in test_ints:
...     if 1000 < i < 2000:
...         print(i)
... 
1984
1991
1023
1999

... and if you want to build a list instead of just printing the filtered elements, create an empty list and append the hits.

>>> result = []
>>> for i in test_ints:
...     if 1000 < i < 2000:
...         result.append(i)
... 
>>> result
[1984, 1991, 1023, 1999]

If you are already comfortable with list comprehensions, the shorter version to write this looks like this:

>>> result = [i for i in test_ints if 1000 < i < 2000]
>>> result
[1984, 1991, 1023, 1999]

Alternatively, the conversion to int could be done on the fly by mapping the int builtin onto your original list test inside a single comprehension.

>>> result = [i for i in map(int, test) if 1000 < i < 2000]
>>> result
[1984, 1991, 1023, 1999]

Personally, I prefer the last solution for its brevity.

1 Comment

(Memory optimization: you could use a generator expression for the conversion or, in the case of Python 2, itertools.imap over map, but these details stroke me as out of scope for OP's current understanding.)
1

Let's start by stating that this just cannot run under python 3 because you cannot compare strings (as contained in your list) to integers anymore without error.

On python 2, all i>1000 tests succeed.

>>> "12">1000
True

Fortunately this has been fixed in python 3 and it avoids those mistakes:

>>> "12">1000
Traceback (most recent call last):
  File "<string>", line 301, in runcode
  File "<interactive input>", line 1, in <module>
TypeError: unorderable types: str() > int()

I suggest to test integers (if you want to keep your list elements as strings, else convert beforehand):

lst = ['135', '2256', '1984', '3985', '1991', '1023', '1999']

print([x for x in lst if 1000<int(x)<2000])

or convert to integer first, then filter:

lst = [int(x) for x in lst]
print([x for x in lst if 1000<x<2000])

using chained comparisons which are very readable in this case.

Comments

0

Check this:

>>> l = ['135', '2256', '1984', '3985', '1991', '1023', '1999']

>>> for i in l:
     if (int(i) > 1000) and (int(i) <  2000):
         print i
  • converting first str to int and then comparing your condition

Comments

0

You are currently facing two problems: your numbers are not really integers, but strings, and the if condition isn't working as you expect.

Starting with the integer problem, you can see that you're handling strings which represents a number by printing their type at the start of the for loop:

for i in test:
    print type(i) # string!

in python is pretty easy to convert strings into integers:

i = int(i) # now 'i' is an integer

In this chunk of code, python will try to convert the string into an integer, and if he can't (i.e. int("Hello World!")), it raises an error.

The second problem is in the logic behind your if condition, but fortunately Python is really similar to english, so we can easily translate our code into spoken language:

for each number in my list,
if the number is higher than 1000, print the number
else if the number is lower than 2000, print the number

So now we can simulate some cases:

our number is 1337
is the number higher than 1000? YES! so - print the number

or

our number is 42
is the number higher than 1000? NO! go on
is the number lower than 2000? YES! print the number

and at last:

our number is 2048
is the number higher than 1000? YES! print the number

so now the problem seems clear.
the english sentence that you want to transform into code is:

for each number in my list, if the number is higher than 1000 and the number is lower than 2000, print the number

I am not going to write you the code, but in other answers you can find it

2 Comments

problem is that OP is comparing strings with integers in python 2.
@Jean-FrançoisFabre didn't noticed - thanks, fixing it right now
0

That is because you are comparing a string with an integer and if the number is not more than 1000 for example the first value: 135, if move to the elif in which 135 < 2000.

What you can try is:

for i in test:
    if 1000 < int(i) < 2000:
        print i

That is given that all your values are integer values.

1 Comment

yes, that works, but real explanation is that OP is comparing strings with integers in python 2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.