Jun-22-2018, 07:29 AM
(Jun-22-2018, 06:57 AM)DRPR Wrote: I am new to python and programming in general.I wanted to write a code which prints the similar elements from 2 lists .For example if a=[1,2,3,4,5] and b=[0,2,4,6] , I would want a c=[2,4]. Here is what I did:
def simi(a,b): a,b,c=[],[],[] for i in a: for j in b: if i==j: c.append(i) else: continue return (c)
- In your function, you overwrite
a
andb
, you have to initialize onlyc
- If you find an equal element - you can stop the search
if i==j: c.append(i) break
- You don't need
else
for an empty action -if
may exist withoutelse
. You only usecontinue
if you have more code in the loop that you want to bypass - and even then it is not advised (unless you want to avoid indenting large block of code)
- It is more efficient to check the presence of an element in a list with an operator
in
- One-letter names are bad practice (with very few exceptions). Variable names are a part of the code documentation, and should tell the code reader their purpose. It is advisable to acquire the habit of naming your variables properly early in the study process
So this is how your function should look like
def similar_elements(list1, list2): similars = [] for elem in list1: if elem in list2: similars.append(elem) return similarsOf course, experienced Pythonista would write it at least as
[elem for elem in list1 if elem in list2]and there are couple of other ways to write it - but that will come in the future.
Good luck with your studies!
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.