(Jun-22-2018, 09:55 AM)DRPR Wrote: I did the method for the experienced pythonista! but it returned a an error:
def simi1(list1,list2): c=[] [elem for elem in list1 if elem in list2] c.append(elem) return(c)Any tips?
Error:NameError: name 'elem' is not defined
I probably should not have shown it (if I hadn't, someone had probably "corrected" me ). I have committed a sin I often berate others for - showing an advanced technique to a newbie without a disclaimer.
This is the proper code
def simi1(list1,list2): return [elem for elem in list1 if elem in list2]or - by
set
, as buran suggesteddef simi1(list1,list2): return set(list1).intersection(list2)The problem with those 2 solutions for you - jumping stages. Mastering loops is a step to mastering list comprehension.
Test everything in a Python shell (iPython, Azure Notebook, etc.)
- Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
- Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
- You posted a claim that something you did not test works? Be prepared to eat your hat.