David Streid
David Streid

Reputation: 724

How do I write conditional for loops in one line in Python?

For example, how could I condense

In [1]: for x in xrange(1,11):
...:     if x%2==0:
...:         print x

into one line?

Edit: Thanks guys! That was exactly what I was looking for. To make this a little more challenging though, is there a way to add elif & else and still have it be on one line?

To use the previous example,

for x in xrange(1,11):
   if x%2==0:
      print x
   else
      print "odd"

Upvotes: 0

Views: 3221

Answers (4)

user2864740
user2864740

Reputation: 61865

This isn't quite the same and isn't "one line", but consider removing the side-effect and using a list filter/comprehension.

evens = [x for x in xrange(1,11) if x % 2 == 0]
print "\n".join(evens)
# or (now a saner "one line", the evens-expr could even be moved in-place)
for x in evens: print x

Upvotes: 1

nrikee
nrikee

Reputation: 1

for x in [y for y in xrange(1,11) if y%2==0]:
  print x

Upvotes: 0

Tom Fenech
Tom Fenech

Reputation: 74596

For your specific example:

for x in xrange(2, 11, 2): print x

More generally, in terms of whether you can nest blocks on one line, the answer is no. Paraphrasing the documentation on compound statements, a "suite" may not contain nested compound statements if it is in the one-line form. A "suite" is the group of statements controlled by a clause (like a conditional block or the body of a loop).

Upvotes: 2

Victor Castillo Torres
Victor Castillo Torres

Reputation: 10811

Maybe something like this:

from __future__ import print_function

map(print, [x for x in xrange(1,11) if x % 2 == 0])

Upvotes: 1

Related Questions