May-21-2020, 12:53 PM
(May-20-2020, 02:40 PM)perfringo Wrote:(May-20-2020, 12:12 PM)hussainmujtaba Wrote: It is more efficient if you convert your list to a set just for comparison purpose. A list can have the same element multiple times, when converting it to a set, it ll only contain element once.
I think that using built-in any() is even more efficient approach. Due to short-circuiting nature it will stop if first match encountered. In real life scenarios this means that if there is a match you don't need to go through all items in list or convert whole list into set. One can craft such a code:
>>> target = 33 >>> lst = [11, 22, 33, 44, 55] >>> match = ['is not', 'is'][any(target == item for item in lst)] >>> f'{target} {match} in the list' '33 is in the list' >>> target = 10 >>> match = ['is not', 'is'][any(target == item for item in lst)] >>> f'{target} {match} in the list' '10 is not in the list'Instead of ['is not', 'is'] one can use ['not', ''] and put 'is' into string but it would be too cryptic for my taste.
I am pretty much sure that the both methods will take the exactly the same time to execute.You can check practically if you want