Creating multiple lists of named tuples based on condition I have created a function which is used to create a list of named tuples. The tuple which is created is dependent on the format of 'instructions' in which there are 3 different formats. Instructions is just a list of lists. I wanted to improve the readability/maintainability of this function and had 3 ideas in mind but not sure how to implement them.


Should the named tuple declarations live somewhere outside the function and be called in somehow?
Should list comprehensions be used?
Could this be set up using a factory pattern instead of using the if statements? How would that be done?


Ignoring the naming convention as it's just generic... any further feedback would be much appreciated.

instructions = [['1'],['2','bob','MATCH'],['3','alice','55']]

def assign_tuple_lists(instructions):
    """Creates named tuple lists from instructions"""

    Items = namedtuple('Items', 'timestamp, user, action')
    Cars = namedtuple('Cars', 'timestamp, user, reserve')                               
    Timing = namedtuple('Timing', 'timestamp')

    items = []
    cars = []
    timing = []
    for instruction in instructions:
        if len(instruction) &lt; 2:
            timing.append(Timing._make(instruction))
        elif instruction[2] == 'MATCH':
            cars.append(Cars._make(instruction))
        else:
            items.append(Items._make(instruction))

    return timing, cars, items


Output:

timing = [Timing(timestamp = '1')]
cars = [Cars(timestamp = '2',user = 'bob',reserve = 'MATCH')]
timing = [Item(timestamp = '3',user = 'alice',action = '55')]
You can make a separate method that decided which type the instruction is:

def get_parser(instruction):
    if len(instruction) &lt; 2:
        return Timing
    if instruction[2] == 'MATCH':
        return Cars
    return Items


and then just use that:

def assign_tuple_lists2(instructions):
    """Creates named tuple lists from instructions"""
    result  = defaultdict(list)
    for instruction in instructions:
        parser = get_parser(instruction)
        result[parser.__name__].append(parser(*instruction))

    return result


this uses a collections.defaultdict instead of separate lists per type


defaultdict(list,
            {'Timing': [Timing(timestamp='1')],
             'Cars': [Cars(timestamp='2', user='bob', reserve='MATCH')],
             'Items': [Items(timestamp='3', user='alice', action='55')]})