This works, but it makes a lot of assumptions about the structure (i.e. only one level of nesting, string ) ...
from itertools import chain lst = ['alfa[1]', 'bravo', ('charlie[7]', 'delta[2]'), 'echo[3]'] flattened = chain.from_iterable([x] if isinstance(x, str) else x for x in lst) result = [x.rsplit('[', 1)[0] for x in flattened]
It becomes more accurate when you give concentrated operations a name:
def flatten(it): return chain.from_iterable([x] if isinstance(x, str) else x for x in lst) def clean(it): return (x.rsplit('[', 1)[0] for x in it) result = list(clean(flatten(lst)))
If you want to stay closer to the code, you can clear it using recursion.
def process(lst, result=None): if result is None: result = [] for item in lst: if isinstance(item, str): result.append(item.rsplit('[', 1)[0]) else: process(item, result) return result result = process(lst)
Edit
More concise thanks to @yoonkwon's inspiration, but note that compiler.ast deprecated and no longer exists in Python 3:
from compiler.ast import flatten result = [item.rsplit('[', 1)[0] for item in flatten(lst)]
source share