Jamie Mcquire
Jamie Mcquire

Reputation: 39

Running a list through a less than to produce shorter list python

a = [0,1,2,3,4,5,6]
for x in a:
  list(x < 4):

Expected Output: [0,1,2,3] Actual Output: [True, True, True, True, False, False, False]

Any idea how to get what I want?

Upvotes: 1

Views: 104

Answers (2)

GLHF
GLHF

Reputation: 4035

a = [0,1,2,3,4,5,6]
print ([x for x in a if x<4])

Output;

[0, 1, 2, 3]
>>> 

Edit after comment: It's called list comprehension.

Upvotes: 8

Mohammed Aouf Zouag
Mohammed Aouf Zouag

Reputation: 17142

You can use filter:

>>> a = [0,1,2,3,4,5,6]
>>> list(filter(lambda x: x < 4, a))
[0, 1, 2, 3]

or itertools.takewhile (in case the list was sorted):

>>> from itertools import takewhile
>>> a = [0,1,2,3,4,5,6]
>>> list(takewhile(lambda x: x < 4, a))
[0, 1, 2, 3]

Upvotes: 5

Related Questions