Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortest code for input

I'm trying to make a shortest code for input with condition as much as possible.
Condition: the number should be greater than 0.
Input: first number determines number of next inputs.
For example:

4
1
-2
3
-4

So i want to append to list() only 1 and 3.

Here is my code:

n=int(input())
t=[]
for i in range(n):
    x = int(input())
    if(x>0):
        t.append(x)
print(t)

I'm wondering if it can be shorter
I had idea, but it was not working as i expected - "syntax error":

n=int(input())
t=[x=int(input()) for x in range(n) if(x)>0)]
print(t)

EDIT: forgot. I'm using python3.1...

like image 735
hradecek Avatar asked Mar 30 '26 16:03

hradecek


1 Answers

Here is one way of doing it:

[x for x in (int(input()) for _ in range(int(input()))) if x > 0]
like image 94
jamylak Avatar answered Apr 01 '26 09:04

jamylak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!