[Tutor] Traversing a two-dimensional "array"(was: (no subject)
Terry Carroll
carroll at tjc.com
Wed Jun 18 21:36:58 CEST 2008
On Wed, 18 Jun 2008, amit sethi wrote:
> Hi , Could you please tell me , how i can traverse a two dimensional array ,
> i am sorry , it must be pretty simple but I am new to python am not able to
> understand.
What many languages would call a two-dimensional array would be
represented in Python as a list of lists; i.e., a list where each item in
the list is itself another list.
For example, if we have a list like this:
>>> list_of_lists = [
... [1, 2, 3, 4],
... ['A', 'B', 'C', 'D'],
... ["I", "II", "III", "IV"]
... ]
>>> list_of_lists
[[1, 2, 3, 4], ['A', 'B', 'C', 'D'], ['I', 'II', 'III', 'IV']]
You can traverse it like this:
>>> for inner_list in list_of_lists:
... print "inner_list is:", inner_list
... for item in inner_list:
... print "item:", item
...
inner_list is: [1, 2, 3, 4]
item: 1
item: 2
item: 3
item: 4
inner_list is: ['A', 'B', 'C', 'D']
item: A
item: B
item: C
item: D
inner_list is: ['I', 'II', 'III', 'IV']
item: I
item: II
item: III
item: IV
>>>
There's no need for each inner list to be of the same length, by the way;
I just made it so for this example.
More information about the Tutor
mailing list