Ethan Bierlein
Ethan Bierlein

Reputation: 3535

Check if a list element is in a list when one of it's elements is unknown

Suppose I have a list like the following.

n = [[1, 3, "String1"], [3, 2, "String2"]]

I want to check if one for one of these elements in the list using in. My problem is that I wouldn't know what the string element of the element would equal. I've already tried the below, but it doesn't work.

import types

# Collection of data
data = [[1, 3, "String1"], [3, 2, "String2"]]

# Check to see if an element with two pre-
# determined numbers, and an unknown string
# exists.
assert [1, 3, types.StringType] in n

This does not work though. How can I do this properly?

Upvotes: 0

Views: 126

Answers (2)

TigerhawkT3
TigerhawkT3

Reputation: 49330

Simplest way I can think of:

assert [1,3] in (l[0:2] for l in n)

or:

assert any([1,3] == l[0:2] for l in n)

Upvotes: 0

wim
wim

Reputation: 363476

>>> data = [[1, 3, "String1"], [3, 2, "String2"]]
>>> class AnyString(str):
...     def __eq__(self, other):
...         return isinstance(other, str)
...     
>>> check = [1, 3, AnyString()]
>>> check in data
True

Upvotes: 1

Related Questions