0

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?

Amin Guermazi
  • 1,632
  • 9
  • 19
jkeeraa
  • 129
  • 2
  • 9

1 Answers1

2

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'])
azro
  • 53,056
  • 7
  • 34
  • 70