nested list-comprehension (python): untangled#venkat

>>> [innerItr for outerItr in [[‘_’+base , base+’Const’]  for base in ‘VectorInteger EquityAssetVolatilitySurface’.split()]  for innerItr in outerItr]

[‘_VectorInteger’, ‘VectorIntegerConst’, ‘_EquityAssetVolatilitySurface’, ‘EquityAssetVolatilitySurfaceConst’]

—– That’s the python IDLE response. Now let’s unravel it. —–

The easy part — the split expression returns a LIST of strings.

[[…] for base in …split()] returns a List of List (LoL). Note You can’t inject into output stream 2 items for each input stream item. List comprehension only supports injecting one item. See P86 [[python essential ref]].

outerItr in [..split()] – the “outerItr” is an iterator and represents each inner List. To open up an inner list, we put for innerItr in outerItr at the END. This resembles a double for-loop – as explained in P85 [[python essential ref]].

First expression inside the outermost [], before the very first “for” is the select-clause. In our case it’s the expression “innerItr”. Like in SQL, this is the last thing parsed. This expression is evaluated inside the double-for-loop

Note the outermost [] pair is required. It makes the entire expression a list-expression. I don’t know exactly what happens if you omit the pair, probably not a good idea.

>>> [outerItr for outerItr in [[‘_’+base , base+’Const’]  for base in ‘VectorInteger EquityAssetVolatilitySurface’.split()]]
>>> [[‘_’+base , base+’Const’]  for base in ‘VectorInteger EquityAssetVolatilitySurface’.split()]
—-> same response
[[‘_VectorInteger’, ‘VectorIntegerConst’], [‘_EquityAssetVolatilitySurface’, ‘EquityAssetVolatilitySurfaceConst’]]

>>> [outerItr[0] for outerItr in [[‘_’+base , base+’Const’]  for base in ‘VectorInteger EquityAssetVolatilitySurface’.split()]]
[‘_VectorInteger’, ‘_EquityAssetVolatilitySurface’]

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s