Thursday, April 2, 2009

Python Hidden features

Image representing stackoverflow as depicted i...Image via CrunchBase

What are the Hidden features of Python, a stackoverflow question asks. Thats a very nice thread in Stackoverflow, as of this writing has 94 answers, many very nice ones. With the kind of community on SO, how could it be any way else. Here are the 2 submissions I made to the the question.
#Simulating the tertiary operator using and and or.
#and and or operators in python return the objects themselves rather than Booleans. #Thus:

In [18]: a = True

In [19]: a and 3 or 4
Out[19]: 3

In [20]: a = False

In [21]: a and 3 or 4
Out[21]: 4

#However, Py 2.5 seems to have added an explicit tertiary operator
In [22]: a = 5 if True else '6' In [23]: a Out[23]: 5
And here is the other one:
#Creating dictionary of two sequences that have related data

In [15]: t1 = (1, 2, 3)

In [16]: t2 = (4, 5, 6)

In [17]: dict (zip(t1,t2))
Out[17]: {1: 4, 2: 5, 3: 6}
Reblog this post [with Zemanta]
blog comments powered by Disqus

Labels