how to append to list in list comprehension

Sayth Renshaw flebber.crue at gmail.com
Sat Oct 1 01:44:16 EDT 2016


On Saturday, 1 October 2016 14:17:06 UTC+10, Rustom Mody  wrote:
> On Saturday, October 1, 2016 at 9:08:09 AM UTC+5:30, Sayth Renshaw wrote:
> > I do like [(f + ['0'] if len(f) < 5 else f) for f in fups ] Rustom, if there are better non list comprehension options I would like to know as generally I find then confusing.
> 
> Two points here — best taken independently:
> 1. List comprehensions are confusing
> 2. When to want/not want them
> 
> 
> For 1 I suggest you (privately) rewrite them with '|' for 'for' and '∈' for 'in'
> Once you do that they will start looking much more like the origin that inspires
> them — set builder notation:
> https://en.wikipedia.org/wiki/Set-builder_notation
> 
> From there I suggest you play with replacing '[]' with '{}' ie actually try
> out set comprehensions and then others like dict-comprehensions — very nifty
> and oft-neglected. And the mother of all — generator comprehensions.
> 
> Of course to check it out in python you will need to invert the translation:
> '|' for 'for' and '∈' for 'in'
> the point of which is to use python as a kind of math assembly language
> *into* which you *code* but not in which you *think*
> 
> For 2 its important that you always keep in front of you whether you want to
> approach a problem declaratively (the buzzword FP!) or imperatively.
> Python is rather unique in the extent to which it allows both
> This also makes it uniquely difficult because its all too easy to garble the 
> two styles as John's .append inside a LC illustrates.
> 
> And the way to ungarble your head is by asking yourself the meta-question:
> Should I be asking "How to solve this (sub)problem?" or more simply
> "What is the (sub)problem I wish to solve?"
> 
> How questions naturally lead to imperative answers; whats to declarative
> 
> You may be helped with [plug!] my writings on FP:
> http://blog.languager.org/search/label/FP
> 
> Particularly the tables in:
> http://blog.languager.org/2016/01/primacy.html

Thank You Rustom



More information about the Python-list mailing list