beoliver beoliver - 3 months ago 7
Python Question

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

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.

Answer

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()