[Tutor] parsing an array
aditya.n.lal at gmail.com
Tue Nov 13 06:55:49 CET 2007
On Nov 13, 2007 8:29 AM, sith . <sith618 at yahoo.com> wrote:
> a = [[0,1,2,3,4,5],[1,2,3,4,5,6]]
> You cannot modify the same array when you are looping through it. You have
> to loop through the copy of the contents :- a[:].
> # Untested code
> for i in a[:]: # You are looping through the copy of contents
> # I'm new I'm going to try and explain my understanding of this code; pls
> correct if wrong
> # i is [0,1,2,3,4,5] and i is the other
> # the loop first goes to the list on the left then goes to the list on the
> for j in i:
> #each element in the sublist is now evaluated
> # first 0 in i then 1 in i then back to 1 in i and then to 2 in
> i--------- is this right?
> # implement your logic with j
> if j < i: # or any dynamic conditional check.
> the first time this loops,
> 0 in the first list or i is evaulated against itself
> what is the next j value for the next loop?
> a[i][j] = j <--------- don't understand this bit
> Does this help you?
> I've looked on the net as well as my book (python dummies), but can't find
> an explantion for nested for loops in nested lists. Would it be possible to
> explain? Thank you.
Not sure but it looks like you want to iterate over an array of array (using
for i in a[:] will make i point to the elements of the list and not its
index. For getting the index you need to use enumerate or just range(len(a))
as in :
for i in range(len(a)) :
# now you can access element as a[i]
for j in range(len(a[i])) :
# now you can access the inner array element as a[i][j]
a[i][j] *= 2
You can use this to modify the array content as well. But do exercise
caution in case of length change.
Or have I completely misunderstood your question ?
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Tutor