Skip to content Skip to sidebar Skip to footer

Python : Extract One Iteration Expression From A Loop With Zip Function

In python3, I have the following loop : for c,z in zip(ax.collections, [0.6, 0.8, 2, 0.7, 0.9, 2]): c.zorder = z I don't understand why a single iteration is not correct by doin

Solution 1:

ax.collections is an iterable of some form, as is the list literal involved. The zip loop is assigning a single value from the list literal to the zorder of a single value from ax.collections. ax.collections itself may not have a zorder attribute at all, and the values in it would not be aware of it even if it did.

To make a single iteration correct (assuming ax.collections is a sequence, rather than an arbitrary iterable), you'd do:

ax.collections[0].zorder = 0.6
# look up elem^^^          ^^^ assign single value to its attribute

ax.collections itself is not modified (only an item in it), and only a single value from the list is assigned. If it helps understand it, for sequences in your example, zip can be considered to behave similarly to this unPythonic loop over indices:

mylist = [0.6, 0.8, 2, 0.7, 0.9, 2]
for i inrange(min(len(ax.collections), len(mylist))):
    c = ax.collections[i]
    z = mylist[i]
    c.zorder = z

It's just that the zip loop is significantly faster, and works with any iterable, not just indexable sequences (and doesn't require the inputs to have names, as indexing does in the above example).

Post a Comment for "Python : Extract One Iteration Expression From A Loop With Zip Function"