Reputation: 437
I'm starting to code in python and I came across this code snippet:
for [x, y] in L:
for ix in range(-1, 2):
for iy in range(-1, 2):
cir = pylab.Circle((x + ix, y + iy), radius=sigma, fc='r')
pylab.gca().add_patch(cir)
at the line 1 I can not understand what is happening because I had never seen anything like it in another programming language. How this works?
for [x, y] in L:
[x, y] is a list? i dont know.
Upvotes: 1
Views: 56
Reputation: 477
L must be a sequence of lists (or tuples) with two elements, which can be iterated over. So whenever for [x,y] in L: is executed, it picks each item in th sequence one by one and enters into the loop.
let the sequence be L = [[2,3], [4,5], ['Jeff', 7]]
Now here what will happen when for [x,y] in L:
will be executed is :- first list in the sequence [2,3] will be picked up and assigned as x
and y
respectively. And in the next iteration x
and y
will get the value 4 & 5 respectively. Like wise in third iteration x
will be Jeff
and y
will be 7.
L = [[2,3], [4,5], ['Jeff', 7]]
count = 0
for [x,y] in L:
count += 1
print " Iteration :- %d, \t x :- %s, \t y:- %s" %(count, str(x), str(y))
Upvotes: 1
Reputation: 405735
Yes, [x, y]
is a list with two elements. For your loop to work, L
must be a list (or other iterable data structure) that contains a bunch of lists with two elements. Each time through the loop one of those lists is copied into [x, y]
, then the individual values of x
and y
are used in the body of the loop.
Try this and see if it makes sense:
L = [ [1, 2], [3, 4] ]
for [x, y] in L:
print x
print y
Upvotes: 0