p2or
p2or

Reputation: 339

Convert a list into a sequence of string triples

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

Answers (3)

ipinak
ipinak

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

Rockybilly
Rockybilly

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

TigerhawkT3
TigerhawkT3

Reputation: 49330

You can use a comprehension:

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

Upvotes: 2

Related Questions