Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if two items are in a list, in a particular order?

Tags:

python

list

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?

like image 798
John Smith Avatar asked Dec 24 '11 15:12

John Smith


People also ask

How do you check if two values are in a list?

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.

How do I check if an element exists in another list?

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.

How do you check if an element in a list is present in another list in Python?

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.


4 Answers

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.

like image 67
eumiro Avatar answered Oct 12 '22 12:10

eumiro


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)
like image 27
Jayae Avatar answered Oct 12 '22 13:10

Jayae


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)
like image 22
Ada Weizmann Avatar answered Oct 12 '22 12:10

Ada Weizmann


[2, 3] in [v[i:i+2] for i in range(len(v) - 1)]
like image 25
Paolo Capriotti Avatar answered Oct 12 '22 11:10

Paolo Capriotti