how to append to list in list comprehension

John Gordon gordon at panix.com
Fri Sep 30 22:18:05 EDT 2016


In <534d5506-1810-4a79-ac8f-95a664d17827 at googlegroups.com> Sayth Renshaw <flebber.crue at gmail.com> 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]

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
gordon at panix.com              B is for Basil, assaulted by bears
                                -- Edward Gorey, "The Gashlycrumb Tinies"




More information about the Python-list mailing list