I have a list of input as follows:
test_list = ['a', ('abc', 'd'), ['efgh', 'i'], 'jkl']
which I need to smooth out, so get rid of the tuple and list as the corresponding second and third elements test_list
Expected Result:
['a', 'abc', 'd', 'efgh', 'i', 'jkl']
I have a problem finding the correct list comprehension. I tried the following 2 examples:
result = [xs if type(xs) is str else x for xs in test_list for x in xs]
print('result', result)
result = [x if ((type(xs) is list) or (type(xs) is tuple)) else xs for xs in test_list for x in xs]
print('result',result)
as you can see, it βsmoothesβ the list, but repeats the last item based on the number of characters in the last item. Example, if the last element test_list
is equal 'jklm'
, then the result
last element is repeated 4 times.
I would like to know if there is a list comprehension that aligns the input list to the expected result without repeating the last element.
source
share