C# to Python

I was suppose to do a task which I could do it in any language and my obvious first choice which is purely due to comfort level is C#. I was set to do it in C# and while reading around one, I noticed one of the recommendation for the task is ‘language not limited to c, java or python’. This intrigued me to check out Python. I always heard lot of good things about Python so I spend an hour going through some basic language rules and semantics. At its core, it is very simple, so I decided to learn Python as a part of the process. Here are few things surprised me since I am coming from C# world.

Normally when you want to access an element in an array, we do it by array[index], which is straight forward. If you want to access the last element in c#, you would do this by array[array.Length – 1]. In Python, you can access it directly as array[-1], I thought it is very clever.

Python also have the for and while loop but what surprised me is the way of using ‘else’ in conjunction with loop. Lets say if you want to break from a loop, you will add a if condition inside the loop and break out. Now, if you want to check after loop if the loop exited normally then you add else at the end of the loop. Have a look at 4.4 in the this link.

This one is not a really surprise still worth mentioning. In C# we have value type and reference type. In Python everything is reference type, but they do have mutable and immutable. Like in C# string is still immutable and the collections like list and dictionary are mutable. On the other hand if you want to create an immutable collection ‘tuple’ will help you there.

The next two things are more to show the power of the language. You can write code as function programming model. You can mix and match between functional and oo style if you want. For example, you can create a function and then assign a variable with a value as parameter which in turn you can use it down the line. Take a look at this article, it explains very well.

The last one is so far the best; in Python it is called ‘List Comprehension’. The idea is very simple, if you want to create a new collection from a collection based on some simple if then else, then you can code the full condition in a single line of code. Take a look at the question answer in the stack overflow. I know we can do the same with simple Linq or lamba, but still it is pretty cool. This is something we use more often then you think.

I will keep you updated on anything new I learn or if you have comments or suggestions please let me know.