Thursday 5 January 2012

Using Python list comprehension

Just a quick example of how I use list comprehension to search for matching entries in two lists (of course there's x amount of ways to do this, and results will vary depending on usage).

# two lists with some matching entries a=['jon','mary','frank'] b=['lewis','frank','jon','clive','betty','toni','jim'] #typical method using for loop with if/in statement results=[] for i in a: if i in b: results.append(i) print results # with list comprehension results=[x for x in a if x in b] print results

1 comment:

  1. nice i too made post like this but relevent to my project & for keeping refernce

    http://goo.gl/J8hbX

    ReplyDelete