How can I replace a text delimited string list item with multiple list items in a python list?

Viewed 2260

Given a list:

mylist = ['dog', 'cat', 'mouse_bear', 'lion_tiger_rabbit', 'ant']

I'd like a one-liner to return a new list:

['dog', 'cat', 'mouse', 'bear', 'lion', 'tiger', 'rabbit', 'ant']
12 Answers

One-liners are over-rated. Here's a solution using a "traditional" for loop.

mylist = ['dog', 'cat', 'mouse_bear', 'lion_tiger_rabbit', 'ant']

out = []
for s in mylist:
    if '_' in s:
        out.extend(s.split('_'))
    else:
        out.append(s)

print(out)

output

['dog', 'cat', 'mouse', 'bear', 'lion', 'tiger', 'rabbit', 'ant']

This also works:

out = []
for s in mylist:
    out.extend(s.split('_'))

It's shorter, but I think the previous version is clearer.

Related