4

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]
Hooked
  • 84,485
  • 43
  • 192
  • 261
Sam
  • 405
  • 2
  • 5
  • 13

3 Answers3

7
word in wordList

Or, if you want to check the 4 first,

word in wordList[:4]
Vincent Savard
  • 34,979
  • 10
  • 68
  • 73
  • i was hoping for something like "word in wordList" but I want to ignore the second element. – Sam Mar 11 '12 at 22:35
  • @Sam: `word in wordList[0] + wordList[2:]` is the most succint way. Just be aware that it creates a new list object, so if your list is expensive, it would be better to iterate. However, the fact that you're skipping an element tells me each index means something; why don't you use another collection type? `namedtuple`? A custom class with `__contains__`? – Daenyth Mar 11 '12 at 22:40
  • Thank you, Daenyth! I'm still new to the language, but I'll have to look into creating a structure. – Sam Mar 11 '12 at 22:42
6

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
robert
  • 3,484
  • 3
  • 29
  • 38
  • I ended up using the frozenset() method, thank you! The original way I did it threw an error because it was a list of lists, but this works perfectly! – Sam Mar 11 '12 at 23:21
1

Have indexList be a list of the indicies you want to check (ie, [0,2,3]) and have wordList be all the words you want to check. Then, the following command will return the 0th, 2nd, and 3rd elements of wordList, as a list:

[wordList[i] for i in indexList]

This will return [wordList[0], wordList[2], wordList[3]].

austin1howard
  • 4,815
  • 3
  • 20
  • 23