26
JohanO
8y

Python is such a elegant language, but why can't I have an if-clause on a simple for-statement when I can have it in a list comprehension??

Comments
  • 10
    aList = range (0,20)
    for a in aList:
    if a < 3:
    print (a)

    Why is this not good enough?
  • 6
    Its simply not as elegant IMO...
  • 0
    That doesn't look elegant to me
  • 3
    @harambae that's dangerously close to SQL!

    I see where I remember SQL. My mind is fscked
  • 0
    It's a matter of sanity, more than anything. The type of a comprehension is defined by its enclosing parenthesis. Round for a generator (lazy), square-ish for list, etc.

    It wouldn't make sense to have more than one syntax to create the same generator comprehension. It'll be confusing as hell, not to mention the added complexity of the python interpreter.
  • 2
    @flag0 DAE think SQL is a beautiful language?
  • 1
    ABAP does this nicely:

    LOOP AT mylist WHERE mylistelement > 3 ASSIGNING <pointer>.

    ENDLOOP.

    Shame about the rest of it, very verbose :(
  • 1
    This is one of the reoccurring requests on python-ideas@python.org
  • 4
    Maybe because they're two completely different things and you having a list comp in the 2nd for loop only makes things O(n^2) ?
  • 2
    First one gets a compared to 3 with every loop iteration, second one returns new iterator with only a(s) < 3 from which for loop is iterated through new a(s)
  • 4
    I'd do

    for a in filter(lambda x: x<3, my_list):
    ...
  • 2
    @eldamir yea. I have to learn to use filter, map and reduce more.
  • 0
    Have you tried Ruby? I think this is possible in Ruby
  • 0
    @afrometal learn, and then don't use them. filter and especially reduce are not idiomatic Python and are hard to understand.
  • 1
    The idiomatic way to do it is with an explicit "if x >= 3: continue"
  • 0
    @elazar is it? I usually avoid continue and break as much as possible in C, they feel... kind of goto-y.
  • 0
    @Gauthier it's not an arbitrary continue. It's immediately at the beginning, and the meaning is obvious.
  • 0
    One thing I really miss in python is being able to use a simple "count++" statement... I know there are more Pythonic ways to do this (also, I fucking hate that word), but this really gets on my nerves as I use this in practically every other language.
  • 0
    There are no postfix operators other than () and [] in Python
  • 0
    @elazar, I know, that's why I said it would be nice to have...
  • 0
    To add a new syntactic category so you can do something that you can already do, using 2 characters instead if 3? ☺
  • 1
    @elazar I usually need 5 (2 for spaces, count += 1), so yes :P
Add Comment