Python -- Multidimensional array and "for" loop
Multidimensional array and Comprehensions
List stores ordered data and it is heterogenous (different datatypes in one list). So python does not support explicitly multidimensional array but you can nest list to get multidimensional array. For example:
a = [[1, 2], [3,4]] a = [[[1, 2] [3, 4]], [[5, 6], [7, 8]]
To store data in a list, one possible method is to use the append() method of list object:
someList = [] for i in range(10) : someList.append(i)
However, this will become more complicated when handling multidimensional array. Can we use some compact method to initialise a multidimensional array such as int a[10][10] in C/C++? The answer is yes by using Comprehensions.
Comprehension can be thought as a compact for loop. A list comprehension goes like:
[expression for variable in list]
To create a list, we can write:
someList = [0 for i in range(10)]
someList = [i * i for i in range(10)]
Then, for multidimensional array, it goes like:
someList = [[i + j for j in range(n)] for i in range(m)]
which is an m * n matrix and can be accesed by:
Unlike C/C++, python's for loop just iterates over the items of any sequence (strings, Unicode strings, lists, tuples, bytearrays, buffers, and xrange objects.). A simple example:
animals = ['cat', 'dog', 'bird'] for a in animals : print a
In python, for can be used with else:
for x in range(5) : print x else : print 'Final x = %d' % (x)
Note that statements in else block will not excute if the for loop exists by break statement.
Python Doc for statements