Reputation: 25
How do I compare a variable to each item in a list and return values that are less than the variable?
x = 150
my_list = [15, 100, 500, 2000, 5000]
So I want to return a list with 15 and 100. I am trying something like the following for loop:
for n in my_list:
if x > my_list[n]:
print("True")
which gives me an index error. I understand why I'm getting the index error, what else can I try?
Upvotes: 0
Views: 639
Reputation: 3518
Cheukting's answer already explains how for loops work in Python. In order to make your new list, first create it as an empty list, and then add the appropriate numbers to it in the for loop.
x = 150
my_list = [15, 100, 500, 2000, 5000]
less_than_x = []
for num in my_list:
if num < x:
less_than_x.append(num)
This could also be accomplished with a list comprehension:
less_than_x = [num for num in my_list if num < x]
Upvotes: 0
Reputation: 6090
Simply use list comprehension:
x = 150
my_list = [15, 100, 500, 2000, 5000]
print ([ y for y in my_list if y < x ])
Output:
[15,100]
Upvotes: 1
Reputation: 33938
Yes and here's the pandas way, which supports logical indexing like you're asking for:
import pandas as pd
x = 150
my_series = pd.Series([15, 100, 500, 2000, 5000])
my_series[my_series > x].tolist()
[500, 2000, 5000]
# Note that if we omitted the `.tolist()` call, we'd get a series with numerical indices, which you don't want
my_series[my_series > x]
2 500
3 2000
4 5000
dtype: int64
If you're going to be doing any non-trivial data work, esp. with multiple columns or tables, recommend you start using pandas, it has a rich set of predefined methods for DataFrame and Series. Base python is very very limited and will quickly drive you nuts.
Upvotes: 0
Reputation: 13
You can use filter
(https://docs.python.org/3/library/functions.html#filter) and then convert it into the list if you need a list:
>>> list(filter(lambda n: x > n, my_list))
[15, 100]
Upvotes: 1
Reputation: 264
When writing a for loop in Python like
for n in my_list:
if x > my_list[n]:
print("True")
n
in each loop would be the item in the list itself rather than the index. for if you print all the n
s out it will be 15, 100, 500, 2000, 5000
not 0, 1, 2, 3, 4
So your code would be:
for n in my_list: # n is the number
if x > n:
print("True")
There are other ways you can get the index of the item instead. For example, using enumerate (see: https://docs.python.org/3/library/functions.html#enumerate)
Upvotes: 1