Average kid
Average kid

Reputation: 7403

How to make a seperate list based on certain numbers from a previous list?

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

Answers (3)

Óscar López
Óscar López

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

derricw
derricw

Reputation: 7036

newlist = [x for x in lists if x > 50]

Read about list comprehensions here

Upvotes: 3

mgilson
mgilson

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

Related Questions