Skip to content

I should have learnt Python before

Python
Tags:

I must admit it:

I should have learnt Python before

Economy in Python is very important, because reducing lines of code doesn’t mean poor understanding of the code. I think is the other way around: the shorter, the better.

Writting a one line sentence like this:

variable = "cadena" if (condicion) else "cadena_alternativa"

executed the same than this (shorter, of course!):

if (condition):

variable = "cadena"


else:


variable = "cadena_alternativa"

That’s one of the coolest features Python has. Another cool this is multiple asignation:

a,b = 0, "hola"

or even better, to swap values between variables, all on one line:

a,b = b,a

You can see a little example here.

Lists

Lists are a powerful feature, and for simple operations for all members of a list, you can do it this way::

a = [3,4]

print  [x*2 for x in a]

Another feature I like when working with lists is map, to transform on  list on another list, once a function is applyed to all elements. To run the same as before using map, just write:

def multi(x): return 2 * x
a = [3,4]
print map(multi, a)

You can see the example here. The result is:

>>>

[6,8]

List management is one of the most powerful characteristics of Python. Recently, I needed a function to select the first 7 characters of a string, removing the character _:

def proceso(matriz):
resultado = []
for fila in matriz:
tmp = str.replace(fila[0:7],"_","")
resultado.append(tmp)
return resultado

The previos function was replaced by this (shorter):

def proceso(matriz):

   return [ str.replace(fila[0:7],"_","") for fila in matriz ]

Even you can add if conditions:

def proceso(matriz):

   return [ str.replace(fila[0:7],"_","") for fila in matriz  if fila == 'hola' ]

Here you have an example of this feature.

Global

Another feature I liked a lot is the fact of “remark” when you are using a global variable inside a function, just by declaring this variable global on the function that use it.

To end with …

I guess that doing the course Introduction to Python on coursera.org has end up convincing me that Python is cool!

Have a nice day!

 

PD: I found this post (it’s long!!) of some one that has ended almost programming exclusively in Python!!

Manejando Datos Newsletter

Noticias, entradas, eventos, cursos, … News, entrances, events, courses, …


Gracias por unirte a la newsletter. Thanks for joining the newsletter.