Wednesday, November 16, 2005

appending to a list

In Perl, you can assign a value to a list at its position, like this:
my @a = ();
$a[@a] = 1;
push @a, 1;


In Python, it seems like you can't do that.
Instead, you can do one of the following (according to my experiments)

a = [ ]
a[len(a):len(a) + 1] = 1
a.append(1)
a += [ 1 ]
a[len(a)] = [ 1 ]

Seems a little counter intuitive that you are assigning a list to a position for setting and that you are getting a number when getting, that is, a[len(a) - 1] gives you a number, but it makes sense if you think of appending a list as sticking a list to a list, versus just putting more numbers in it.

In Perl, you can do array slices like this:
@a[0, 3, 5]

How would you do this in Python?

Wednesday, November 09, 2005

Design Mistake?

Despite people's raving about Python's OO support, I think it's a design mistake that functions are mixed into the language for some reason unknown to me. For example, instead of calling string.length in other languages, you call len(string). Most other string operations are part of the string class, but why not lenght?

Another example of oddity, in dealing with unicode you can encode a string using the encode method of a unicode string:
u"你好吗“.encode("utf-8")

To convert back to unicode, you need to do this:
unicode(u"你好吗“.encode("utf-8"), "utf-8")

array slices

A good way to think of the negative indices of array slices:

>> spam = 'spam' * 5;
>> spam[-1] <--- this is essentially spam[len(spam) - 1]
>> spam[-4:-2] <-- this is [len(spam) - 4: len): len(spam) - 2]

Also, how can you remember if
spam[1:2] means element 1 and 2 or element 1 only?

A good way to remember this is to imagine you are cutting a cake, and both indices indicate the border that you should cut it at, with the border index starting from 0 for the first slice. So instead of thinking 1 as cake slice #1, think of it as the left side of slice #1, and 2 as the right side of slice #1. So you are getting slice 1 of the cake after this operation.

So to recap:
spam[0] - you are taking the whole slice
spam[0:2] - you are slicing the cake at border 0 and border 2. So you get element 0 and 1.