Six Reasons to Love Python
Reading language documentation is usually dry and offers few *good* surprises. While “Python in a Nutshell” was not exactly exciting, the language offers some features that you might gloss over if you just jumped in and started hacking. Here is a brief list of six little things that I found most interesting.
Note: If you are new to python, and want to try out some of the functions I discuss here, check out the web-based interactive python shell at shell.appspot.com (no download required).
6. Else clauses in Loops and Try…Catch
Every language has an else clause for if statements, and python is no exception, but not many languages have an else clause in loop structures. For example:
for i in range(10):
if i == 11: break
else:
print "11 was not found"
The else clause executes when the loop terminates naturally, without calling break (this also works with while loops). In the loop above, “11 was not found” is printed because i only ranges from 0 to 9 and break will never be executed. Else has similar functionality for try…catch:
try:
value + ''
except TypeError:
print "value is not a string"
else:
print "value is a string"
Like in loops, the else executes when the try clause terminates normally. In both cases the else clause is optional.
5. Sequences
In Python, a sequence is a container of ordered items. Basic sequences include lists, dictionaries (name-value pairs), tuples and strings. Sequences are very important in Python, and can be thought of as an evolution of arrays. Each sequence has it’s own declaration syntax built into the language:
aList = [1,2,3,4,5]
aTuple = (1,2,3,4,5)
aString = "12345"
aDict = {'a':1,
'b':2,
'c':3,
'd':4,
'e':5,}
Negative indexing allows you to access a sequence from any direction, for example:
print aList[1] # prints 2
print aList[-1] # prints 5
Slicing lets you select subsets from a sequence:
print aList[1:3] # prints 2,3
print aList[:3] # prints 1,2,3
print aList[0:5:2] # prints odd values 1,3,5
print aList[1:5:2] # prints even values 2,4
The syntax is sequence[start:end:stride]. Start is exclusive, and end is inclusive. So [1:5] means 2,3,4,5. Omitting start causes the slice to begin at the first item in the sequence, omitting end defaults to the last item in the sequence and omitting step defaults step to 1. By using this syntax, you can select a nice variety of numeric patterns out of a sequence without a loop.
4. Assignment
There aren’t many surprises left in variable assignment, however Python does have some nice improvements, even if not entirely original. Multiple targets:
X = Y = 1
Both X and Y are assigned the value 1, this works just like C++. It’s a nice and simple feature that I always missed in .NET.
Unpacking assignment:
# assume that coord is the tuple (0, 1)
x,y = coord
Now x = 0 and y = 1. This can be used with any sequence, not just tuples. Another type of unpacking assignment allows you to juggle two variables without using a temp variable:
x,y = y,x
# the alternative would be:
temp = x
x = y
y = temp
3. Iterators
Iterators are nothing new, but Python’s obsessive dedication to them is refreshing. In most languages, when you learn about arrays, you typically learn some form of the following code:
for i as integer = 0 to array.length
foo &= array(i)
next
or
for(int i = 0; i <= array.length; i++)
{
foo += array[i]
}
Which leads to lots of off-by-one errors (did you see the bug when you read the code above?). The "pythonic" way to loop through a sequence is a paradigm shift from the old standard: instead of using a index to access an array, iterators are preferred whenever possible.
for item in array:
foo += item
Of course, iterators are available in other languages, and while this shift seems simple, you feel it when writing code. The fact that Python wants you to use iterators *by default* is an important distinction. In fact, there is no indexed loop in the language. This type of loop is accomplished by iterating over the range (or xrange) function:
for i in range(len(array)):
foo += array[i]
But notice here, that range defaults to exclude the final item (Range(5) returns [0,1,2,3,4]), so it is still harder to make off-by-one errors even when using an index.
2. List Comprehensions
List comprehensions (LCs) are available in many languages, including .NET in the form of LINQ. The builtin support for sequences in Python make LCs even more powerful. The syntax for an LC is
[ expression for target in iterable lc-clauses]
The square brackets here are part of the syntax. Here are a few examples:
aList = [1,2,3,4,5,6,7,8,9]
# basic syntax example, not doing much
# returns a list of all items in aList
[x for x in aList]
# returns a list of all items incremented by 1
[x+1 for x in aList]
# this uses an LC if clause
# returns a list of items > 8
[x for x in aList if x > 8]
# strings are also sequences
# ''.join() converts a list into a string
# returns "str", letters greater than n in aphabet
''.join([ch for ch in "astring" if ch > 'n'])
# slicing a string with a step of 2
# returns "SECRET"
''.join([ch.upper() for ch in "asbeccdreeftg"[1::2] ])
This gets even more interesting when using lists of objects. Of course, this functionality could be represented as a loop with an if statement and a temp variable, but this syntax is very nice and compact.
1. Significant Whitespace
Whitespace indentation defines variable scope. For example:
for x in seq:
# loop body is indented
print x
# no longer in loop body because
# indentation is at a different level
The reason I like the idea of significant whitespace is because it:
1) Forces developers to use standard indentation, making the code more readable.
2) Eliminates the need for "ok, I'm done" signals like "End Function" or "}". These are extraneous keystrokes that don't help the developer, they help the compiler and lower the overall efficiency of the language.
Significant whitespace also has a down side: mixing tabs and spaces confuses the interpreter and will bring you to the brink of insanity. But using a good tool (like Eclipse) eliminates this issue.
Conclusion
Python is not a revolutionary language. In fact, most of its features have been borrowed from other languages. The thing that sets python apart is the way these features are applied and the dedication by the Python developers to make common tasks in the language as clear and concise as possible.
Tagged Tags: Python on May 27, 2008 at 2:08 pm




