Given two different python lists we need to find if the first list is a part of the second list.
With map and join
We can first apply the map function to get the elements of the list and then apply the join function to cerate a comma separated list of values. Next we use the in operator to find out if the first list is part of the second list.
Example
listA = ['x', 'y', 't'] listB = ['t', 'z','a','x', 'y', 't'] print("Given listA elemnts: ") print(', '.join(map(str, listA))) print("Given listB elemnts:") print(', '.join(map(str, listB))) res = ', '.join(map(str, listA)) in ', '.join(map(str, listB)) if res: print("List A is part of list B") else: print("List A is not a part of list B")
Output
Running the above code gives us the following result −
Given listA elemnts: x, y, t Given listB elemnts: t, z, a, x, y, t List A is part of list B
With range and len
We can design a for loop to check the presence of elements form one list in another using the range function and the len function.
Example
listA = ['x', 'y', 't'] listB = ['t', 'z','a','x', 'y', 't'] print("Given listA elemnts: \n",listA) print("Given listB elemnts:\n",listB) n = len(listA) res = any(listA == listB[i:i + n] for i in range(len(listB) - n + 1)) if res: print("List A is part of list B") else: print("List A is not a part of list B")
Output
Running the above code gives us the following result −
Given listA elemnts: ['x', 'y', 't'] Given listB elemnts: ['t', 'z', 'a', 'x', 'y', 't'] List A is part of list B