-5

What would be the fastest to iterate list x to check if any of its characters are listed in y?

x=['cat','dog','fish']
y=['a','b','b']
David
  • 8,449
  • 1
  • 22
  • 32
alphanumeric
  • 17,967
  • 64
  • 244
  • 392

3 Answers3

1

You can convert y to a set and then iterate over x to see if any of y is in it, like this

print any(any(item in word for word in x) for item in set(y))
# True

any short-circuits immediately after finding a match, so this would be very efficient.

Apart from that we can convert both of them to sets, and then check if they are disjoint sets, like this

print not {char for word in x for char in word}.isdisjoint(set(y))
# True

isdisjoint also short-circuits if it determines that both the sets are not disjoint sets.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
0

Use list comprehension:

>>> x=['cat','dog','fish']
>>> y=['a','b','b']
>>> [char in word for char in y for word in x]
[True, False, False, False, False, False, False, False, False]
>>> 

This prints the above output for all the characters and words: True because 'a' is in 'cat', and False for the rest, because nothing else exists.

Here is an example that is easier to read:

>>> x = ['cat', 'dog', 'fish']
>>> y = ['a', 'b', 'c']
>>> [(word, char, char in word) for char in y for word in x]
[('cat', 'a', True), ('dog', 'a', False), ('fish', 'a', False), ('cat', 'b', False), ('dog', 'b', False), ('fish', 'b', False), ('cat', 'c', True), ('dog', 'c', False), ('fish', 'c', False)]
>>> ["It is %s that %s is in %s" %(str(char in word), char, word) for char in y for word in x]
['It is True that a is in cat', 'It is False that a is in dog', 'It is False that a is in fish', 'It is False that b is in cat', 'It is False that b is in dog', 'It is False that b is in fish', 'It is True that c is in cat', 'It is False that c is in dog', 'It is False that c is in fish']
>>> 

Answering your comment, yes there is way:

>>> x = ['cat', 'dog', 'fish']
>>> y = ['a', 'b', 'c']
>>> myList = []
>>> [myList.append(word) for word in x for char in y if char in word]
[None, None]
>>> myList
['cat', 'cat']
>>> list(set(myList))
['cat']
>>> 

The reason why the list comprehension prints [None, None] is because the built-in method append() doesn't return anything, hence the None.

A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
  • Remember to accept an answer which helped you (the green tick next to the answer, it gives you +2 reputation :)) – A.J. Uppal May 01 '14 at 04:56
  • Is there any CPU utilization 'release' versus nested 'for word in x: for char in y: if char in word: myList.append(word)' approach? – alphanumeric May 01 '14 at 04:57
0

why isn't this enough for comparison?

>>> x=['cat','dog','fish']
>>> y=['a','b','b']
>>> x == y
False
>>> b = ['a','b', 'b']
>>> x == b
False
>>> y == b
True
Ciasto piekarz
  • 7,853
  • 18
  • 101
  • 197