Reputation: 2933
Is there a simple way to append a list if X is a string, but extend it if X is a list? I know I can simply test if an object is a string or list, but I was wondering if there is a quicker way than this?
Upvotes: 8
Views: 5382
Reputation: 2312
mylist.extend( [x] if type(x) == str else x )
or maybe the opposite would be safer if you want to catch things other than strings too:
mylist.extend( x if type(x) == list else [x] )
Upvotes: 11
Reputation: 362
buffer = ["str", [1, 2, 3], 4]
myList = []
for x in buffer:
if isinstance(x, str):
myList.append(x)
elif isinstance(x, list):
myList.extend(x)
else:
print("{} is neither string nor list".format(x))
A better way would be using try-except
instead of isinstance()
Upvotes: 0
Reputation: 76788
I do not think so. extend
takes any iterable as input, and strings as well as lists are iterables in python.
Upvotes: 0