Reputation: 7403
Hey guys trying to finish my program. Here is my code:
lists = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
#I want to make a new list consisting of only numbers above 50 from that list
if any(list > 50 for list in list):
newlists = list
I don't know how to do it. I'm doing something wrong, can anyone help me?
Upvotes: 1
Views: 69
Reputation: 236124
Two options. Using list comprehensions:
lst = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
[x for x in lst if x > 50]
And using filter
in Python 2.x:
filter(lambda x: x > 50, lst)
Or using filter
in Python 3.x, as pointed in the comments, filter
returns an iterator in this version and if needed, the result needs to be converted to a list first:
list(filter(lambda x: x > 50, lst))
Anyway, the result is as expected:
=> [60, 70, 80, 90, 100]
Upvotes: 2
Reputation: 7036
newlist = [x for x in lists if x > 50]
Read about list comprehensions here
Upvotes: 3
Reputation: 310097
something like this will work:
new_list = [ x for x in lists if x > 50 ]
This is known as a "list comprehension" and can be extremely handy.
Upvotes: 3