I was wondering if there was a better way to put:
if word==wordList[0] or word==wordList[2] or word==wordList[3] or word==worldList[4]
word in wordList
Or, if you want to check the 4 first,
word in wordList[:4]
Very simple task, and so many ways to deal with it. Exciting! Here is what I think:
If you know for sure that wordList is small (else it might be too inefficient), then I recommend using this one:
b = word in (wordList[:1] + wordList[2:])
Otherwise I would probably go for this (still, it depends!):
b = word in (w for i, w in enumerate(wordList) if i != 1)
For example, if you want to ignore several indexes:
ignore = frozenset([5, 17])
b = word in (w for i, w in enumerate(wordList) if i not in ignore)
This is pythonic and it scales.
However, there are noteworthy alternatives:
### Constructing a tuple ad-hoc. Easy to read/understand, but doesn't scale.
# Note lack of index 1.
b = word in (wordList[0], wordList[2], wordList[3], wordList[4])
### Playing around with iterators. Scales, but rather hard to understand.
from itertools import chain, islice
b = word in chain(islice(wordList, None, 1), islice(wordList, 2, None))
### More efficient, if condition is to be evaluated many times in a loop.
from itertools import chain
words = frozenset(chain(wordList[:1], wordList[2:]))
b = word in words
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