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?
append() adds a single element to the end of the list while . extend() can add multiple individual elements to the end of the list. Argument: . append() takes a single element as argument while .
append adds its argument as a single element to the end of a list. The length of the list itself will increase by one. extend iterates over its argument adding each element to the list, extending the list.
As we can see, extend with list comprehension is still over two times faster than appending.
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] )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With