how to append to list in list comprehension
Sayth Renshaw
flebber.crue at gmail.com
Fri Sep 30 23:37:58 EDT 2016
> > 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]
>
> However there's no reason to use a list comprehension here. The whole
> point of list comprehensions is to create a *new* list, which you don't
> appear to need; you just need to modify the existing fups list.
>
> --
> John Gordon A is for Amy, who fell down the stairs
B is for Basil, assaulted by bears
> -- Edward Gorey, "The Gashlycrumb Tinies"
You are right John in that I don't want a new list I just wish to modify in-place to acheive the desired output.
I had no direct desire to use list comprehension just seemed an option.
Ultimately once it works I will abstract it into a function for other lists that will have a similar issue.
def listClean(fups)
holder = [(f + ['0'] if len(f) < 5 else f) for f in fups ]
return holder[0], holder[1], holder[2], holder[3], holder[4]
and then call it in my csv.writer that I have, which currently errors quite correctly that it cannot write index[4] as some of my lists fail it.
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.
Cheers
Sayth
More information about the Python-list
mailing list