Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending lists using list comprehension in python

So let's say I have list items = ['abc', 'def', 'tre'].

Now I want to insert a flag before each of list items.

E.g the new list items2 should be ['-g', 'abc', '-g', 'def', '-g', 'tre'].

I could read the list and append each one after appended the flag but I want to start doing it the python way.

What I came up with is:

items2.extend(['-g', i] for i in items )

What this gives me a list with smaller lists:

items2 = [['-g', 'abc'], ['-g', 'def'], ['-g', 'tre']]

I understand that this is because it would be equivalent to saying

items2.extend([ ... ] , [ ... ], [ ... ])

Any ideas about this? Thanks

like image 894
AsadSMalik Avatar asked Feb 12 '26 19:02

AsadSMalik


1 Answers

[j for i in items for j in '-g', i]
like image 123
Robᵩ Avatar answered Feb 15 '26 10:02

Robᵩ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!