Python Scientific lecture notes, Release 2012.
3 (EuroScipy 2012)
For collections of numerical data that all have the same type, it is often more efficient to use the array type
provided by the numpy module. A NumPy array is a chunk of memory containing fixed-sized items. With
NumPy arrays, operations on elements can be faster because elements are regularly spaced in memory and more
operations are perfomed through specialized C functions instead of Python loops.
Python offers a large panel of functions to modify lists, or query them. Here are a few examples; for more details,
see [Link]
Add and remove elements:
>>> l = [1, 2, 3, 4, 5]
>>> [Link](6)
>>> l
[1, 2, 3, 4, 5, 6]
>>> [Link]()
6
>>> l
[1, 2, 3, 4, 5]
>>> [Link]([6, 7]) # extend l, in-place
>>> l
[1, 2, 3, 4, 5, 6, 7]
>>> l = l[:-2]
>>> l
[1, 2, 3, 4, 5]
Reverse l:
>>> r = l[::-1]
>>> r
[5, 4, 3, 2, 1]
Concatenate and repeat lists:
>>> r + l
[5, 4, 3, 2, 1, 1, 2, 3, 4, 5]
>>> 2 * r
[5, 4, 3, 2, 1, 5, 4, 3, 2, 1]
Sort r (in-place):
>>> [Link]()
>>> r
[1, 2, 3, 4, 5]
Note: Methods and Object-Oriented Programming
The notation [Link]() ([Link](), [Link](3), [Link]()) is our first example of object-oriented
programming (OOP). Being a list, the object r owns the method function that is called using the notation ..
No further knowledge of OOP than understanding the notation . is necessary for going through this tutorial.
Note: Discovering methods:
In IPython: tab-completion (press tab)
In [28]: r.
r.__add__ r.__iadd__ r.__setattr__
r.__class__ r.__imul__ r.__setitem__
r.__contains__ r.__init__ r.__setslice__
r.__delattr__ r.__iter__ r.__sizeof__
r.__delitem__ r.__le__ r.__str__
r.__delslice__ r.__len__ r.__subclasshook__
r.__doc__ r.__lt__ [Link]
2.2. Basic types 12