Home > Mobile >  Pyhton 3 - are there cases where it's OK to alter the container you're looping on with a f
Pyhton 3 - are there cases where it's OK to alter the container you're looping on with a f

Time:03-29

In the following code I pass a list of an unknown number of inside lists to a function that sorts each inside list and then zips the lists and returns a list of the zip object.

def myZip (LS):
    for i in LS:
        i.sort()
    return list(zip(*LS))

        
L1=[3,1,2]
L2=[5,6,4]
L3=['a','b','c']
print(myZip([L1, L2, L3]))


    

I know it's a bad idea to alter the container you're looping on. My question is does this also apply to the situation I described here?

CodePudding user response:

The answer to your Question is no... I mean there are always exceptions, but the answer is still no; it's not a good idea, nor is it acceptable.

Now, the answer to the thing you typed after answering the question is perfectly fine, acceptable, etc. Because you aren't giving an example of altering the container you're looping through; rather, you are altering items in that list - which is pretty standard really.

  • Related