1

I have the following code:

stuart = 0
kevin = 0    
for itr, char in enumerate(word_list):
    if char in "aeiou":
        kevin += len(word_list) - itr
    else:
        stuart += len(word_list) - itr

Can I write the if/else statement as a ternary operator?

I tried the following to no avail:

(kevin if (char in "aeiou") else stuart) += len(word_list) - itr

and

kevin += len(word_list) - itr if char in "aeiou" else stuart += len(word_list) - itr

Is there a way to write this as a ternary operator for more compact code?

zthomas.nc
  • 3,689
  • 8
  • 35
  • 49

3 Answers3

9

Put your variables in a dictionary instead, and then you can vary the key you are assigning to:

names = {'stuart': 0, 'kevin': 0}
for itr, char in enumerate(word_list):
    names['kevin' if char in "aeiou" else 'stuart'] += len(word_list) - itr

You can't otherwise use a conditional expression to switch out variables.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
5

It is not possible to change the variable on left-hand side of assignment. However you can use the globals() trick to assign to a global variable, though this is frowned upon, thus never do this:

stuart = 0
kevin = 0    
globs = globals()
for itr, char in enumerate(word_list):
    globs['kevin' if char in 'aeiou' else 'stuart'] += len(word_list) - itr

For most perfomant code, one can gather the counts in a list of 2 items, and index them by char in "aeiou" which will choose index 1 (because True == 1!) for vowels and index 0 (as False == 0) for consonants; then unpack these to desired variables. Also, the length of word_list will be constant, but since Python cannot know this, the code will perform better if len(word_list) is placed outside the loop:

counts = [0, 0]
length = len(word_list)
for itr, char in enumerate(word_list):
    counts[char in "aeiou"] += length - itr

stuart, kevin = counts
2
    kevin, stuart = ( kevin + len(word_list) - itr, stuart ) if char in "aeiou" else ( kevin, stuart + len(word_list) - itr )
Arnial
  • 1,433
  • 1
  • 11
  • 10