I've got a feeling that I will be told to go to the 'beginner's guide' or what have you but I have this code here that goes
does = ['my','mother','told','me','to','choose','the']
it = ['my','mother','told','me','to','choose','the']
work = []
while 5 > len(work):
for nope in it:
if nope in does:
work.append(nope)
print (work)
And I get
['my', 'mother', 'told', 'me', 'to', 'choose', 'the']
Why is this? And how do I convince it to return
['my', 'mother', 'told', 'me']
We can club the Python sort() method with the == operator to compare two lists. Python sort() method is used to sort the input lists with a purpose that if the two input lists are equal, then the elements would reside at the same index positions.
Method 3: Use a list comprehension and set to Find the Difference Between Two Lists in Python. In this method, we convert the lists into sets explicitly and then simply reduce one from the other using the subtract operator.
The method which is formally applied to calculate the similarity among lists is finding the distinct elements and also common elements and computing it's quotient. The result is then multiplied by 100, to get the percentage.
You could try something like this:
for nope in it:
if len(work) < 5 and nope in does:
work.append(nope)
else:
break
The problem with your code is that it does the check of the work's length, after having looped through all the items of it
and having added all of them that are in does
.
You can do:
does = ['my','mother','told','me','to','choose','the']
it = ['my','mother','told','me','to','choose','the']
work = []
for nope in it:
if nope in does:
work.append(nope)
work = work[:4]
print (work)
It's just making the list without checking the length, then cutting it and leaving only the 4 first elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With