Saturday, September 22, 2012

Some Python Nuances

Me and my partner have been struggling a little bit with the current project due to some misunderstood Python nuances. Our current implementation to the Project File Dependencies problem on Sphere calls for a list of lists. Seems like standard procedure right? We should just use Python's overloaded * operator to initialize the data structure like so:

matrix_size = 5 
matrix = [[]] * matrix_size

Which, if we print out the matrix, we get the following output:


[[], [], [], [], []]

It seems like it is working just fine, but if we do a simple operation, like add a number to the list at index 0, funny things start to happen. See the following operation:

matrix[0].append("?")

and the contents of the matrix afterwards:

[['?'], ['?'], ['?'], ['?'], ['?']]

How does this make sense? What were the creators of Python thinking? Why does this functionality make sense? I do not understand why this is the case. It is acting like each list in the matrix is just a reference to one matrix. In order to get the functionality we wanted we had to do something like the following:

matrix = [[] for i in range(matrix_size)]

which seems to be working just fine because a new list is created for each index.

Another issue we were having lies in the annoyance that Python has no increment or decrement operators! And if you try to use them, nothing happens! It is valid Python syntax!

It is all ok though. With every new language comes a little bit of headache. As far as interpreted languages go, Python is coming to be one of my favorites so far, and as long as I can minimize future headaches like the first one in this post I think I will be quite alright.


No comments:

Post a Comment