Reputation: 339
I'd like to convert a list like:
["Red", "Green", "Blue"]
into a tuple sequence of string triples:
[("RED", "Red", ""), ("GREEN", "Green", ""), ("BLUE", "Blue", "")]
Until now I always use this method:
def list_to_items(lst):
items = []
for i in lst:
items.append((i.upper(), i, ""))
return items
But it feels a bit ugly. Is there a nicer / more pythonic way of doing this?
Upvotes: 1
Views: 2938
Reputation: 6039
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 info http://www.secnetix.de/olli/Python/list_comprehensions.hawk
Upvotes: 3
Reputation: 4510
Similar to list comprehension, but a bit different.
This is the map function.
lst = ["Red", "Green", "Blue"]
new_lst = map(lambda x: (x.upper(), x, ""), lst)
It basically changes every element of a list one-by-one according to the function you enter as the first parameter. Which is in this case:
lambda x: (x.upper(), x, "")
If you don't have an idea what lambda is, it is almost like in the high school math:
f(x) = (x.upper(), x, "") # basically defines a function in one line.
Upvotes: 3
Reputation: 49330
You can use a comprehension:
def list_to_items(lst):
return [(item.upper(), item.title(), '') for item in lst]
Upvotes: 2