Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Python one liner? if x in y, do x

Tags:

python

ruby

numbers = [1,2,3,4,5,6,7,8,9]
number = 1

Can I write the following on one line?

if number in numbers:
    print number

Using the style of ruby:

puts number if numbers.include?(number)

I have tried:

print number if number in numbers

But the syntax is invalid.

like image 799
beoliver Avatar asked Nov 30 '22 06:11

beoliver


2 Answers

The python syntax is yes_value if test else no_value. With optional parentheses for clarity, you can say this:

print "Searching...", ("Found it" if n in numbers else "Not found")

I agree, the syntax is incredibly unintuitive. Even C conditional expressions are easier to read.

like image 34
alexis Avatar answered Dec 06 '22 08:12

alexis


Python is Python, Ruby is Ruby. My advice is not to try writing one in the other.

Python does not have Ruby's / Perl's "postfix if", and the Pythonic way to write this is the one you've already got.

But if you really must, this will work:

if number in numbers: print number

It is against the official style guide, PEP8, though:

  • Compound statements (multiple statements on the same line) are generally discouraged.

    Yes:

    if foo == 'blah':
        do_blah_thing()
    do_one()
    do_two()
    do_three()
    

    Rather not:

    if foo == 'blah': do_blah_thing()
    do_one(); do_two(); do_three()
    
like image 71
Thomas Avatar answered Dec 06 '22 10:12

Thomas