Flattening A List Or A Tuple In Python. Not Sure What The Error Is
Solution 1:
You've assigned the built-in list
to a list instance in your function, so the type check no longer works properly for list objects.
You should use a different name for the accumulator list, say, lst
:
defflatten(t):
lst = []
for i in t:
iftype(i) != listandtype(i) != tuple:
lst.append(i)
else:
lst.extend(flatten(i))
return lst
OTOH, you could do both checks at once using isinstance
which also ensures that the objects you're running your checks against are actually types:
...
ifnotisinstance(i, (list, tuple)):
...
Solution 2:
You masked the name list
:
list = []
...
if(type(i) != list and ...
type(i)
is never going to be equal to []
.
Use a different name for your list:
result = []
You also want to use isinstance()
instead of type()
with equality tests:
defflatten(t):
result = []
for i in t:
ifnotisinstance(i, (list, tuple)):
result.append(i)
else:
result.extend(flatten(i))
returnlist
this would have told you much earlier that you were not comparing with a type:
>>> list = []
>>> isinstance(['foo'], (list, tuple))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: isinstance() arg 2 must be a typeortuple of types
The exception is thrown because []
is not a type.
You could use a generator here to avoid the need to append or extend a new list object repeatedly. If you put the isinstance()
type check outside the loop you can support non-sequences with the same function:
defflatten(t):
ifnotisinstance(t, (list, tuple)):
yield t
returnfor i in t:
yieldfrom flatten(i)
result = list(flatten(some_sequence_or_single_value))
Post a Comment for "Flattening A List Or A Tuple In Python. Not Sure What The Error Is"