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?

0 Comments:

Post a Comment

<< Home