How to improve this code?
Simon Forman
sajmikins at gmail.com
Fri Sep 18 13:26:08 EDT 2009
On Sep 14, 9:08 pm, Oltmans <rolf.oltm... at gmail.com> wrote:
> Hello,
>
> Is there someway I can improve the following code(pythonically)?
> (Copying from IDLE)
> match=[1,2,3,4,5]
>
> def elementsPresent(aList):
> result=False
> if not aList:
> return False
> for e in aList:
> if e in match:
> result=True
> else:
> result = False
> return result
> elementsPresent([6,7,8,9,5]) # should return True because 5 is
> present in list named match.
>
> Is there somehow I can improve code in elementsPresent()? I'm not a
> very good programmer but I sense that idea of using a variable named
> 'result' inside elementsPresent() doesn't sound very good. Any ideas
> will be highly appreciated.
>
> Thanks,
> Oltmans
It's not really relevant to this particular task (since you want to
stop after finding an 'e' in match) but whenever you're doing
something like this:
if e in match:
result = True
else:
result = False
You can just assign the result of the boolean expression directly to
your result:
result = e in match
Regards,
~Simon
More information about the Python-list
mailing list