Reputation: 74084
Having a list like this:
['foo','spam','bar']
is it possible, using list comprehension, to obtain this list as result?
['foo','ok.foo', 'spam', 'ok.spam', 'bar', 'ok.bar']
Upvotes: 17
Views: 13420
Reputation: 16775
With list comprehensions, you're creating new lists, not appending elements to an existing list (which may be relevant on really large datasets)
Why does it have to be a list comprehension anyway? Just because python has them doesn't make it bad coding practice to use a for-loop.
Upvotes: 1
Reputation: 879391
In [67]: alist = ['foo','spam', 'bar']
In [70]: [prefix+elt for elt in alist for prefix in ('','ok.') ]
Out[70]: ['foo', 'ok.foo', 'spam', 'ok.spam', 'bar', 'ok.bar']
Upvotes: 33