2

Suppose I have a list:

items = ['matt', 'zen', 'a', 'b', 'c', 'cat', 'dog']

if elem in items 
`if 'a' 'b' 'c' found then return 1

Whenever elem finds 'a', 'b', 'c' in the list and return a value. Is there a way to define the list in such a way? I don't want to have multiple if conditions (if it can be avoided).

3
  • 2
    Do you require the ordering to be the same or just that all those elements exist? Commented May 24, 2013 at 13:12
  • The ordering doesn't matter Commented May 24, 2013 at 13:14
  • Changed str name to items, str is a builtin Commented May 24, 2013 at 13:23

3 Answers 3

6

To check if every item is in items

>>> items = ['matt', 'zen', 'a', 'b', 'c', 'cat', 'dog']
>>> {'a', 'b', 'c'}.issubset(items)
True

Inside a for loop, still taking advantage of the fast (O(1) amortized) lookup speeds of sets:

find = {'a', 'b', 'c'}
for elem in items:
    if elem in find:
        # do stuff
Sign up to request clarification or add additional context in comments.

10 Comments

Note this adds the restriction of hashable items.
@jamylak Is there another way to do this, because what I am doing is this: for elem in items return a proper value for elem
@JamesHallen I thought you needed to assure they were all inside items, anyway I added a for loop check
Is it possible to use the in function for example, maybe combine 'a'+'b'+'c' to 'abc' and define subset = ['a'] and if subset in 'abc' -the do whatever
@JamesHallen if any(x in string for x in ('at', 'bat', 'cat'))
|
2

You can use the subset operator for simple objects such as strings:

>>> items = ['matt', 'zen', 'a', 'b', 'c', 'cat', 'dog']
>>>> {'a', 'b', 'c'} < set(items)
True

Here is a general case :

>>> items = ['matt', 'zen', 'a', 'b', 'c', 'cat', 'dog']
>>> all(x in items for x in (['a'], 'b', 'c'))
True

It still works even though we have an unhashable type in the container.

Comments

1

Or

for elem in 'abc':
    if elem in str

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.