1

Looking for assistance from the experts here to help make good choices in a program that I am creating. Which of the two approaches for creating a list appears more Pythonic and readable to you? Or is there a better way that I could be doing this?

Approach #1 - list comprehension

def test_func(*args):
    s = 'Country name: United {nm}'
    l = [s.format(nm='States') if x is 'us' 
         else s.format(nm='Arab Emirates') if x is 'uae'
         else s.format(nm='Kingdom') if x is 'uk' 
         else 'Unknown' for x in args]
    return l

# execute
test_func('us', 'uk', 'uae')

# results
['Country name: United States',
 'Country name: United Kingdom',
 'Country name: United Arab Emirates']

Approach #2 - for loop

def test_func(*args):
    s = 'Country name: United {nm}'
    l = []
    for arg in args:
        if arg is 'us':
            l.append(s.format(nm='States'))
        elif arg is 'uk':
            l.append(s.format(nm='Kingdom'))
        elif arg is 'uae':
            l.append(s.format(nm='Arab Emirates'))
        else:
            l.append(s.format(nm='Unknown'))
    return l

# execute
test_func('us', 'uk', 'uae')

# results
['Country name: United States',
 'Country name: United Kingdom',
 'Country name: United Arab Emirates']
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
user9074332
  • 2,336
  • 2
  • 23
  • 39
  • Aside: don't use `is` for string comparisons. See [here](https://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is-in-python) on the difference between `is` and `==`. – DSM Aug 31 '18 at 02:30
  • The more pythonic approach would be to use a `dict` mapping here, like the answer below, but in general, nested conditional expressions are not very readable IMO. For-loops are pretty much always pythonic. – juanpa.arrivillaga Aug 31 '18 at 02:38
  • #2 - `United Unknown`? :) – OneCricketeer Aug 31 '18 at 02:42

1 Answers1

6

You are mapping at the wrong level. Use a dict like:

Code:

def test_func(*args):
    mapping = {
        'us': 'United States',
        'uae': 'United Arab Emirates',
        'uk': 'United Kingdom',
    }
    return ['Country name: {}'.format(mapping.get(x, 'Unknown')) for x in args]

# execute
print(test_func('us', 'uk', 'uae', 'xyzzy'))

Results:

[
    'Country name: United States', 
    'Country name: United Kingdom', 
    'Country name: United Arab Emirates',
    'Country name: Unknown'
]
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135