python - First common element from two lists -


x = [8,2,3,4,5] y = [6,3,7,2,1] 

how find out first common element in 2 lists (in case, "2") in concise , elegant way? list can empty or there can no common elements - in case none fine.

i need show python new it, simpler better.

upd: order not important purposes, let's assume i'm looking first element in x occurs in y.

this should straight forward and effective gets (for more effective solution check ashwini chaudharys answer , effective check jamylaks answer , comments):

result = none # go trough 1 array in x:      # element repeats in other list...     if in y:          # store result , break loop         result =         break 

or event more elegant encapsulate same functionality functionusing pep 8 coding style conventions:

def get_first_common_element(x,y):     ''' fetches first element x common both lists         or return none if no such element found.     '''     in x:         if in y:             return      # in case no common element found, trigger exception     # or if no common element _valid_ , common state of application     # return none , test return value     # raise exception('no common element found')     return none 

and if want common elements can this:

>>> [i in x if in y] [1, 2, 3] 

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -