Blog of me. I’m Alexander Jones.

Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

01 March 2010

PHP wart of the day

Just spent about a half hour debugging this. It's such a shame that if you try to do anything neat in PHP, stupid behaviour foils your plan:

php > $n = NULL;
php > var_dump($n['something']);
NULL
php > var_dump($n[0]);
NULL

How this makes any sense is beyond me. It even happens if $n is FALSE...

Python, for comparison, throws an exception sanely:

In [1]: n = None
In [2]: n['something']
TypeError: 'NoneType' object is unsubscriptable

24 February 2010

Python tip: enumerate(list) vs. xrange(len(list))

For a long time, when wanting a counting variable with which to index some list in a Python loop, I've used for i in xrange(len(some_list)). However, I've since discovered the built-in enumerate function, so you can instead do for i, item in enumerate(some_list). This has the benefit of already giving you effectively item = some_list[i] for each iteration of the loop, and also working on iterators that don't necessarily have a length. (enumerate simply gives you an iterator that returns each item of the input collection back together with a counting number. Far too simple!)

Hopefully this will help someone, but if not, it’ll remind me later!