Python array literal syntax sugar similar to Perl and Ruby Background


Python (version 2.7.2)


Problem


You want to specify an array in your code.
You want to use the 'syntax sugar' available in Ruby and Perl.
You are a fanatic about readable code but also saving keystrokes.


Solution


Python Triple-quoted string
Python splitlines
Python list comprehension


Pitfalls


The solution may look ugly or un-Python-ish


Question

Are there any refactorings, suggestions or comments on this approach?

### ********************
## setup an array using append
ary_names = []
ary_names.append('alpha')
ary_names.append('bravo')
ary_names.append('charlie')
ary_names.append('delta')
ary_names.append('echo')

### ********************
## setup an array using triple-quoted string
ary_names = [
  item.strip() for item in  
  """

  alpha
  bravo
  charlie
  delta
  echo

  """
  .splitlines()
  if(not item.strip()=='')
]

"""
Here is a ruby example for comparison

ary_names = %w[
  alpha
  bravo
  charlie
  delta
  echo      
]
"""
If you call split with no arguments, it will split on any whitespace and drop any empty elements. Knowing that, it's as simple as this:

ary_names = """
    alpha
    bravo
    charlie
    delta
    echo
""".split()


If you have only five short elements, you may want to put them all on one line:

ary_names = 'alpha bravo charlie delta echo'.split()


Of course, you'd only want to do that if it fits easily on one line.