Convert list to string sequence

I would like to convert a list, for example:

["Red", "Green", "Blue"] 

into an alternating sequence of lines:

 [("RED", "Red", ""), ("GREEN", "Green", ""), ("BLUE", "Blue", "")] 

So far, I always use this method:

 def list_to_items(lst): items = [] for i in lst: items.append((i.upper(), i, "")) return items 

But that seems a little ugly. Is there a nicer / more pythonic way to do this?

+1
source share
3 answers

You can use understanding:

 def list_to_items(lst): return [(item.upper(), item.title(), '') for item in lst] 
+2
source

The code in the return statement is called list comprehension.

 def list_to_items(items): return [(i.upper(), i, "") for i in items] 

You can find more information http://www.secnetix.de/olli/Python/list_comprehensions.hawk

+3
source

Like understanding a list, but a little different.

This is a map .

 lst = ["Red", "Green", "Blue"] new_lst = map(lambda x: (x.upper(), x, ""), lst) 

It basically modifies each item in the list one by one according to the function you entered as the first parameter. What in this case:

 lambda x: (x.upper(), x, "") 

If you have no idea what lambda is , it almost looks like high school math:

 f(x) = (x.upper(), x, "") # basically defines a function in one line. 
+3
source

All Articles