First impression on Python
Just started learning Python for a couple of days, found it seem to be a elegant and powerful language.
For example, there’s a problem set of the MIT online course, to let you use for loop output a sequence of number like this:
10, 8, 6, 4, 2,
I know it is easy with basic programming handling method. But I was asking myself, since range(1,5) can give you:
1, 2, 3, 4,
then what is the shortest code to output an array like this:
4, 3, 2, 1,
So how? Tried something like range(5,1) or range (1, 5,-1) it didn’t work. (Later I found actually “range(4,0,-1)” will do)
Then I turned to google and found one can actually do this:
4, 3, 2, 1
My impression on this was like:
This is brilliant and elegant, also perhaps very efficient. However, after looking more discussion on the stackoverflow page, I found an interesting thing for example:
import numpy as np a = np.array(range(1,11)) b = a[:] c = a[::-1] print c a = 100 b = 101 print c
and the output of it is:
[10 9 8 7 6 5 4 3 2 1]
[ 10 9 8 7 6 5 4 101 100 1]
which means c changes by not doing direct change on itself.
This is because “when you create c you are creating a view into the original array. You can then change the original array, and the view will update to reflect the changes,” as stated by someone on that stackoverflow page. This could be extremely useful, and it feels python give me back the freedom of easily using index or pointer-like functionalities, which could mean that one can probably write very elegant code to do efficient and memory saving operations, easily. It seems to have the potential.
Also, as someone from this stackoverflow post said:
“I commonly work with >10GB 3D arrays of uint8’s, so I worry about this a lot… Numpy (seems to be a python math package) can be very efficient at memory management if you keep a few things in mind.”
And he also mentioned other ways to save time and space such as how to avoid making a copy of an array and so on. I will need to go back to this post again sometime later, to get a better understanding of the language.
And so far my first impression on Python is like this: