Python expands or adds a list when necessary

Is there an easy way to add a list if X is a string, but expand it if X is a list? I know that I can just check if the object is a string or a list, but I was wondering if there is a faster way than this?

+4
source share
3 answers

mylist.extend ([x] if type (x) == str else x)

or maybe vice versa, it would be safer if you want to catch things other than strings as well:

mylist.extend (x if type (x) == list else [x])

+6
source

I do not think so. extend takes any iteration value as input, and strings as well as lists are iterable in python.

0
source
 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)) 

It is best to use try-except instead of isinstance()

0
source

Source: https://habr.com/ru/post/1336482/


All Articles