[Tutor] a list comp

Alan Gauld alan.gauld at blueyonder.co.uk
Thu Dec 11 11:46:25 EST 2003


> def merge_list():
>         newlist = []
>         [newlist.append(index) for index in del_list if index
not in keep_list]

What this does is build a list of return codes from [].append()
Probably all Nones. But as a side effect it populates newlist

>         return newlist

So this works...



> and this is not:
>
> def merge_list():
>         newlist = []
>         return [newlist.append(index) for index in del_list if
index not in keep_list]

This returns the list of return values - not very useful.
Try this:

def merge_list(del_list, keep_list):
  return [index for index in del_list if index not in keep_list]

The comprehension creates a list you don't need to initialise
one separately. Also its good to pass in the del and keep lists
to avoid risk of side effects and make the function reusable
with other names....

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list