Why loop variable is not updated in python -
this code printing 1 2 4 5..my question why p not updated new array @ 3rd iteration
p = [1, 2, [1, 2, 3], 4, 5] each in p: if type(each) == int: print each else: p = each actually precise when debugged code saw updating value of p each variable not reinitialised again.
because of if type(each) == int: line. third element list ([1, 2, 3]) , not int, doesn't print anything.
now comes changing p variable: p name object, not object itself. if p = each inside loop, doesn't affect original object you're looping through, changes name p local name, points different object. round of loop ends, loop continues business original object looping through.
so, notice p = each doesn't change existing object (the p you're looping through), creates new local name p points value of each.
what want this:
p = [1, 2, [1, 2, 3], 4, 5] each in p: if isinstance(each, list): x in each: print x else: print each this again, isn't recursive, , you'd need function that:
def print_elements(iterable): element in iterable: if isinstance(element, list): print_elements(element) else: print element if want unpack values 1 list use them other printing, should use this:
def recursive_unpack(iterable): element in iterable: if isinstance(element, list): yield recursive_unpack(element) else: yield element why i'm using isinstance() instead of type(): differences between isinstance() , type() in python
also, if want apply iterables (my last example) , not lists: in python, how determine if object iterable?
Comments
Post a Comment