how to append to list in list comprehension

Rustom Mody rustompmody at gmail.com
Fri Sep 30 23:28:33 EDT 2016


On Saturday, October 1, 2016 at 7:48:19 AM UTC+5:30, John Gordon wrote:
> In Sayth Renshaw  writes:
> 
> > I want to go threw and for each index error at [4] append a 0.
> 
> You want to append 0 if the list does not have at least 5 items?
> 
> > p = re.compile('\d+')
> > fups = p.findall(nomattr['firstup'])
> > [x[4] for x in fups if IndexError fups.append(0)]
> > print(fups)
> 
> > Unsure why I cannot use append in this instance
> 
> Because that's incorrect syntax.
> 
> > how can I modify to acheive desired output?
> 
>     for f in fups:
>         if len(f) < 5:
>             f.append(0)
> 
> Or, if you really want to use a list comprehension:
> 
>       [f.append(0) for f in fups if len(f) < 5]

Wrong

fups = [['0', '0', '0', '0'],
['0', '0', '0', '0'],
['0', '0', '0', '0'],
['0', '0', '0', '0'],
['0', '0', '0', '0'],
['0', '0', '0', '0'],
['7', '2', '1', '0', '142647', '00'],
['7', '2', '0', '1', '87080', '00'],
['6', '1', '1', '1', '51700', '00'],
['4', '1', '1', '0', '36396', '00'] ]

>>> [f.append(0) for f in fups if len(f) < 5] 
[None, None, None, None, None, None]

Or right if you re-squint:

>>> fups
[['0', '0', '0', '0', 0], ['0', '0', '0', '0', 0], ['0', '0', '0', '0', 0], ['0', '0', '0', '0', 0], ['0', '0', '0', '0', 0], ['0', '0', '0', '0', 0], ['7', '2', '1', '0', '142647', '00'], ['7', '2', '0', '1', '87080', '00'], ['6', '1', '1', '1', '51700', '00'], ['4', '1', '1', '0', '36396', '00']]
>>> 

Which is to say that imperative code — .append — inside a comprehension 
is a bad idea

One comprehension way to do it would be:

>>> [(f + ['0'] if len(f) < 5 else f) for f in fups ]
[['0', '0', '0', '0', '0'], ['0', '0', '0', '0', '0'], ['0', '0', '0', '0', '0'], ['0', '0', '0', '0', '0'], ['0', '0', '0', '0', '0'], ['0', '0', '0', '0', '0'], ['7', '2', '1', '0', '142647', '00'], ['7', '2', '0', '1', '87080', '00'], ['6', '1', '1', '1', '51700', '00'], ['4', '1', '1', '0', '36396', '00']]



More information about the Python-list mailing list