Because of if type(each) == int:
line. Your third element is a list ([1, 2, 3]
) and not an int, so it doesn't print anything.
Now what comes to changing the p
variable: p
is just a name for an object, not the object itself. If you do p = each
inside the for loop, it doesn't affect the original object you're looping through, it just changes the name p
to a local name, which points to a different object. As soon as that round of the loop ends, your for loop continues to do its business with the original object you were looping through.
So, notice that p = each
doesn't change the existing object (the p
you're looping through), it simply creates a new local name p
which points to the value of each
.
What you most likely want is something like this:
p = [1, 2, [1, 2, 3], 4, 5]
for each in p:
if isinstance(each, list):
for x in each:
print x
else:
print each
This then again, this isn't recursive, and you'd need a function for that:
def print_elements(iterable):
for element in iterable:
if isinstance(element, list):
print_elements(element)
else:
print element
If you want to unpack the values into one list to use them for something other than printing, you should use something like this:
def recursive_unpack(iterable):
for element in iterable:
if isinstance(element, list):
yield from recursive_unpack(element)
else:
yield element
Why I'm using isinstance()
instead of type()
: Differences between isinstance() and type() in python
Also, if you want this to apply to all iterables (my last example) and not just lists: In Python, how do I determine if an object is iterable?