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']
00:12 But Python has developed a syntax called a list comprehension, which simplifies the code needed to perform that same action. It doesn't use . append() at all, but it's important enough that you really should see it in this course while you're looking at how to populate lists.
Method #1 : Using list comprehension + startswith() In this method, we use list comprehension for traversal logic and the startswith method to filter out all the strings that starts with a particular letter. The remaining strings can be used to make a different list.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With