Say I have a list v = [1, 2, 3, 4, 3, 1, 2]
. I want to write a function, find_pair
which will check if two numbers are in the list and adjacent to each other. So, find_pair(v, 2, 3)
should return True
, but find_pair(v, 1, 4)
should return False
.
Is it possible to implement find_pair
without a loop?
Use the all() function to check if multiple values are in a list, e.g. if all(value in my_list for value in multiple_values): . The all() function will return True if all of the specified values are in the list and False otherwise.
The most convenient way to check whether the list contains the element is using the in operator. Without sorting the list in any particular order, it returns TRUE if the element is there, otherwise FALSE. The below example shows how this is done by using 'in' in the if-else statement.
We can use the in-built python List method, count(), to check if the passed element exists in the List. If the passed element exists in the List, the count() method will show the number of times it occurs in the entire list. If it is a non-zero positive number, it means an element exists in the List.
v = [1,2,3,4,3,1,2]
any([2,3] == v[i:i+2] for i in xrange(len(v) - 1))
While @PaoloCapriotti's version does the trick, this one is faster, because it stops parsing the v
as soon as a match is found.
This is probably a bit of a round about way to do it, but you could use (with your variable v above):
' 2, 3' in str(v)
v = [1, 2, 3, 4, 3, 1, 2]
def find(x, y, v):
return (x, y) in zip(v, v[1:])
print find(2, 3, v)
print find(1, 4, v)
[2, 3] in [v[i:i+2] for i in range(len(v) - 1)]
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