I have a list that looks something like this:
data = ['1', '12', '123']
I want to produce a new list, that looks like this:
result = ['$1', '1', '$2', '12', '$3', '123']
where the number after the $
sign is the length of the next element.
The straightforward way to do this is with a for
loop:
result = []
for element in data:
result += [f'${len(element)}'] + [element]
but I was wondering if it's possible to do it in a more elegant way - with a list comprehension, perhaps?
I could do
result = [[f'${len(e)}', e] for e in data]
but this results in a list of lists:
[['$1', '1'], ['$2', '12'], ['$3', '123']]
I could flatten that with something like
result = sum([[f'${len(e)}', e] for e in data], [])
or even
result = [x for xs in [[f'${len(e)}', e] for e in data] for x in xs]
but this is getting rather difficult to read. Is there a better way to do this?
You can do it with two loops:
result = [item for s in data for item in (f"${len(s)}", s)]
['$1', '1', '$2', '12', '$3', '123']