[Tutor] Change dictionary value depending on a conditional statement.
Terry Carroll
carroll at tjc.com
Thu Feb 14 00:53:09 CET 2008
I don't think I saw anyone point this out yet, but, using "list" as a
variable name is a bad idea, because it hides the list method.
>>> x = list("abcdefg")
>>> x
['a', 'b', 'c', 'd', 'e', 'f', 'g']
This works. You now have a variable named "x" that is a list.
>>> list = list("hijklmnop")
>>> list
['h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']
This works, sort of. You now have a variable named "list" that is a list.
But since you reused the name "list," it can no longer point to the list
function.
>>> y = list("qrstuv")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
And so this fails.
On Tue, 12 Feb 2008, Norman Khine wrote:
> Thank you all, very nice.
>
> Steve Willoughby wrote:
> > Kent Johnson wrote:
> >> Try
> >> list.append({'id': 'name', 'link': ('YY','XX')[total > 0]})
> >
> > I'd caution against that, though. It's clever and cute, sure, but the
> > meaning of it is obfuscated enough to be unpythonic because [total > 0]
> > as a subscript doesn't mean anything unless you know you're taking
> > advantage of an implementation detail that booleans are 0 for false and
> > 1 for true. No matter how reliable that fact may be, I don't think that
> > value should be stuck into a numeric context like that.
> >
> >> Or, in Python 2.5,
> >> list.append({'id': 'name', 'link': ('XX' if total > 0 else 'YY')})
> >
> > This is much more clear, and would IMHO be fine.
> >
> >
> >
> > _______________________________________________
> > Tutor maillist - Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list