Python Forum
boolean result of loop - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: boolean result of loop (/thread-2648.html)

Pages: 1 2


RE: boolean result of loop - wavic - Apr-01-2017

I don't want anything but @scaperen do. On one line. A universal approach. If it can be done, I think it will lose readability.


RE: boolean result of loop - buran - Apr-01-2017

(Apr-01-2017, 11:20 AM)wavic Wrote: I don't want anything but @scaperen do. On one line. A universal approach.
Actually he didn't say oneliner...


RE: boolean result of loop - ichabod801 - Apr-01-2017

(Apr-01-2017, 12:07 PM)buran Wrote: he didn't say oneliner

Yeah, he did. Post #3. That's what I was responding to. Perhaps I should have quoted.


RE: boolean result of loop - Skaperen - Apr-02-2017

hopefully, it can be done in one line.  if not, then two lines would be good.  but if unreadable, then it's not worth it.

when we know some (any) classic logic, then it would be nice to express it succinctly.  IMHO, a loop to look for some condition (or value) and yield (or use) it, falls into this category.  this is at the level of structure.  so, a language having nothing more than structure, could include this.  those with more, should.  with the features python has, it should be easy.


RE: boolean result of loop - Skaperen - Apr-02-2017

you can do

if 'foo' in d:
    something = d['foo']
else:
    something = False
or you can do

something = d.get('foo',False)
see... 1 statement instead of 4

bonus points: who can show how to do this in 1 statement for a sequence

if x < len(s):
    something = s[x]
else:
    something = False



RE: boolean result of loop - Ofnuts - Apr-02-2017

(Apr-02-2017, 02:52 AM)Skaperen Wrote: bonus points: who can show how to do this in 1 statement for a sequence

if x < len(s):
    something = s[x]
else:
    something = False

something=s[x] if x < len(s) else False
or
something=[False,s[x]][x < len(s)]



RE: boolean result of loop - wavic - Apr-02-2017

The second way, isn't it deprecated?


RE: boolean result of loop - micseydel - Apr-02-2017

(Apr-02-2017, 11:34 PM)wavic Wrote: The second way, isn't it deprecated?
Deprecated usually means it was recommended at the time :)

It was an ok hack, but the behavior is not the same. When you build the list, its contents get evaluated, whereas with the longer form or the ternary expression it evaluates only what it needs to. This is important if there are side effects (aka EVIL) or even if there is a performance cost associated with one or both values.


RE: boolean result of loop - wavic - Apr-02-2017

I confess that I've never used this.


RE: boolean result of loop - ichabod801 - Apr-03-2017

I used it once on the old board and everyone got mad at me. ; )