Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prepend prefix to list elements with list comprehension

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']
like image 440
systempuntoout Avatar asked Jul 25 '10 20:07

systempuntoout


People also ask

Can you append in list comprehension python?

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.

How do you filter a string starting with Python?

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.


1 Answers

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']
like image 120
unutbu Avatar answered Oct 19 '22 04:10

unutbu