Reputation: 937
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
Upvotes: 2
Views: 269
Reputation: 3503
Another simple way is to loop through your list and insert after every element.
for i in range(len(items)):
items.insert((i*2)+1,'-g')
As you insert your length up to the insertion point doubles, so you need to put your next element at (i*2)+1
Upvotes: 1
Reputation: 51990
As a complement to other excellent zip
based answers, you might use itertools.repeat()
instead of "counting" items:
>>> items = ['abc', 'def', 'tre']
>>> list(itertools.chain(*zip(itertools.repeat('-g'), items)))
# ^^^^^^^^^^^^^^^^^^^^^^
# repeat as much as needed
['-g', 'abc', '-g', 'def', '-g', 'tre']
And if you don't like zip, an alternative:
>>> list(itertools.chain(*[('-g', i) for i in items]))
['-g', 'abc', '-g', 'def', '-g', 'tre']
Upvotes: 2
Reputation: 188014
One approach would be using zip
:
>>> items = ['abc', 'def', 'tre']
>>> zip(['-g', '-g', '-g'], items)
[('-g', 'abc'), ('-g', 'def'), ('-g', 'tre')]
After that, you can use itertools.chain
to flatten the list:
>>> list(itertools.chain(*zip(['-g', '-g', '-g'], items)))
['-g', 'abc', '-g', 'def', '-g', 'tre']
Note that due to function call overhead, this is quite slow, compared to a simple list comprehension:
In [17]: %timeit [j for i in items for j in '-g', i]
1000000 loops, best of 3: 923 ns per loop
In [18]: %timeit list(itertools.chain(*zip(['-g', '-g', '-g'], items)))
100000 loops, best of 3: 2.67 µs per loop
So for performance and clarity, I suggest you use Robᵩ answer.
Upvotes: 3