5
Some More Python Essentials
5.1 Lists and Tuples: Alternatives to Arrays
We have seen that a group of numbers may be stored in an array that we may treat
as a whole, or element by element. In Python, there is another way of organizing
data that actually is much used, at least in non-numerical contexts, and that is a
construction called list.
Some Properties of Lists A list is quite similar to an array in many ways, but
there are pros and cons to consider. For example, the number of elements in a list is
allowed to change, whereas arrays have a fixed length that must be known at the time
of memory allocation. Elements in a list can be of different type, so you may mix,
e.g., integers, floats and strings, whereas elements in an array must be of the same
type. In general, lists provide more flexibility than do arrays. On the other hand,
arrays give faster computations than lists, making arrays our prime choice unless
the flexibility of lists is needed. Arrays also require less memory use and there is a
lot of ready-made code for various mathematical operations. Vectorization requires
arrays to be used.
A list has elements that we may use for computations, just like we can with array
elements. As with an array, we may find the number of elements in a list with the
function len (i.e., we find the “length” of the list), and with the array function
from numpy, we may create an array from an existing list:
In [1]: x = list(range(6, 11, 1))
In [2]: x
Out[2]: [6, 7, 8, 9, 10]
In [3]: x[0]
Out[3]: 6
In [4]: x[4]
Out[4]: 10
In [5]: x[0] + x[1]
Out[5]: 13
© The Author(s) 2020
S. Linge, H. P. Langtangen, Programming for Computations - Python,
Texts in Computational Science and Engineering 15,
https://doi.org/10.1007/978-3-030-16877-3_5
103
Précédent

- 124/350

Suivant