Search code examples
pythonpython-3.xif-statementoptimizationprettytable

How to do same commands but in different iteration styles with if-condition? (Python, code optimization)


So, I've got this code:

    t = PrettyTable(['first', 'second'])
    if condition:
        for i in data_set[::-1]:
            t.add_row([i['first'], i['second'])
            # ... (multiple other commands)
    else:
        for i in data_set:
            t.add_row([i['first'], i['second'])
            # ... (same multiple commands as above)

and I want to shorten the code, so that I only have to write the commands once. Is that possible?


Solution

  • Just use the condition to get the correct iterable then do your stuff

    items = data_set if condition else data_set[::-1]
    
    for i in items:
        t.add_row([i['first'], i['second'])