Saturday, January 5, 2013

Coding Fun: Python Lists

As you might know, I recently started to learn Python programming. It all started because of a recent project I worked on as an lean, architect and senior engineer. It involved heavy .NET development on a frontend WPF application controlling a high resolution Canon EOS camera. While I was responsible for executing the .NET app, I had to integrate it with the backend system, which was done in Python. The project was driven by retail installations and events, and I had to travel around the world deploying and supporting the system.

My coding background is mostly in .NET (although I have also programmed with Java, RPG/RPGLE, Perl, PHP, Visual Basic, JavaScript, a bit of iOS and Android and a few others). However, during the installations and events, I had to deal on several occasions with the Python scripts and programs running on the platform. During those times, I started to think about learning Python more seriously. Additionally, several of my colleagues have started to get into it, so I think is a good time to dive in.

Ok, enough of my traditional talking, lets get to the code. So, I have been using a the Khan Academy Windows 8 app for my python lessons. One of the first things I have been playing around is with lists, and let me tell you, they are fun! (by the way, here is a good link to get started with Python 3).

Now according to the documentation, “Lists are mutable sequences, typically used to store collections of homogeneous items (where the precise degree of similarity will vary by application)”. Lists in Python, as in .NET, are zero based structures.

You can create a list by using square brackets or the type constructor. Lets see some examples.

Using Square Brackets:

`  1: [1,2,3]`
`  1: a = [1,2,3]`

Using Type Constructor:

`  1: #creates a list of literals ['1', '2', '3']  2: b = list('123')`
`  1: #creates a list of integers [1,2,3]  2: c = list((1,2,3))`

Now, you can make two variables point to the same list:

`  1: # create a new reference to the list   2: # 'a' and 'd' point to the same list instance  3: # if you modify a, then d will be modified too  4: d = a`

Or, create another instance of the list:

`  1: # by using the square brackets syntax, you are creating a new  2: # instance of the list. If you modify 'a', 'e' will remain   3: # the same, since it is a different copy of the list  4: e = a[:]`

So, now that we know how to create list instances and references, lets see how we can retrieve and modify specific values.

Retrieving a list value:

`  1: # retrieving a value from the list   2: # using the element index  3: # the result will be '2' (list is [1,2,3])   4: a[1] `

Modifying an element of the list:

`  1: # use the element index to modify the value  2: # list was [1,2,3]  3: a[0] = 0  4: # now the list is [0,2,3]`

Now, we can apply operations over list elements, and this can be quite a lot of fun. Check this out:

`  1: # multiplication operand acting over two integers  2: # result is 6 (3 * 2)  3: a[2] * 2`
`  1: # apply a division operation over two integers  2: # result is 1.0  3: a[1] / 2`
`  1: # same operation over a non-divisible value  2: # result is 0.0  3: a[0] / 2`
`  1: # triggering a zero-division error  2: # will throw a ZeroDivisionError  3: a[1] / 0`

Now, this is expected. However, what happens when you start mixing types in the same list? Lets create a list of integers and literals.

`  1: # create a list of integers and literals  2: # list will be ['zero', 1, 'two', 3]  3: f = ['zero', 1, 'two', 3]`

This is interesting. In .NET you need to specify the type of the elements of the list. The only way you could mix up different types, will be to create a list of “objects”, but then you need to use casting to be able to perform operations over the elements. In Python, this works differently. You are able to throw in elements of different types and then perform operations over them without using casting. Lets take a look using our previous list.

`  1: # retrieve element at position 1: 1  2: # multiply it by 2. The result is 2  3: f[1] * 2`
`  1: # retrieve element at 0: 'zero'  2: # multiply it by 2.  3: # the result is actually: 'zerozero'  4: f[0] * 2`

Now, that is unexpected. Types are not being enforced, and it seems like an overloaded operator, which understands that multiplying a literal, is actually repeating that literal ‘X’ number of times. However, you can get errors if you perform an invalid operation:

`  1: # retrieve element at 0: 'zero'  2: # divide it between 1  3: # the operation throws the following error  4: # TypeError: unsupported operand type(s) for /: 'str' and 'int'  5: f[0] / 1`

The best part of learning a new language is that it makes you think about this that you take for granted in the languages you already know. I can say that playing around with lists on Python made me go back and review what I knew about C# lists.

I will continue to dig deeper into the different structures and operations, and how Python treats them. For now, I’ll conclude with just a few more examples of operations you can use over lists.

`  1: # adding an element at the end of the list  2: # in this case, adding int 4 to the 'a' list  3: a.append(4)`
`  1: # clears all elements from the list  2: # result is []  3: a.clear()`
`  1: # recreate the list  2: a = [0,2,3,4]  3: # insert a new element on a given position  4: # result is [0, 1, 2, 3, 4]  5: a.insert(1,1)`
`  1: # return (and remove) last element of the list  2: # result is 4  3: a.pop()`

You also have functions like copy, count, sort, extend, index, remove and reverse. Go ahead and play with them to see what you can get.

Ok, that’s that for now. I’m just starting to play around with Python and the different data structures. Please feel free to leave any comments, corrections, lessons, or whatever you want to share in the comments sections. I’d really appreciate your time to share them.