How to Check If One of the Following Items Is in a List

How to check if one of the following items is in a list?

>>> L1 = [2,3,4]
>>> L2 = [1,2]
>>> [i for i in L1 if i in L2]
[2]

>>> S1 = set(L1)
>>> S2 = set(L2)
>>> S1.intersection(S2)
set([2])

Both empty lists and empty sets are False, so you can use the value directly as a truth value.

How to check if all of the following items are in a list?

Operators like <= in Python are generally not overriden to mean something significantly different than "less than or equal to". It's unusual for the standard library does this--it smells like legacy API to me.

Use the equivalent and more clearly-named method, set.issubset. Note that you don't need to convert the argument to a set; it'll do that for you if needed.

set(['a', 'b']).issubset(['a', 'b', 'c'])

Check if all items in list are one of the items in another list

One way is using sets:

set(User_input).issubset(List_Permitted_Characters)

If this is all you are using List_Permitted_Characters for, you should store is as a set anyway, since the sequential information is irrelevant.

one-liner to check if at least one item in list exists in another list?

There are many ways to do this. The most direct translation is:

any_in = lambda a, b: any(i in b for i in a)

You could also use various things involving sets, such as:

any_in = lambda a, b: bool(set(a).intersection(b))

(which depends on the elements of a being hashable, but if that's true, it'll probably be faster to make a set of the larger out of a and b for either of these approaches).

Edit: isdisjoint is better than intersection for Python 2.6 and above, as noted by various people below. Glad to learn about that. :)

What’s the best way to check if a list contains an item other than specified item?

With Stream IPA you can achieve that by using terminal operation allMath() that takes a predicate (function represented by boolean condition) and checks whether all elements in the stream match with the given predicate.

The code will look like that:

public static void main(String[] args) {
List<String> items1 = List.of("apple", "apple", "apple"); // expected true
List<String> items2 = List.of("apple", "orange"); // expected false

System.out.println(items1.stream().allMatch(item -> item.equals("apple")));
System.out.println(items2.stream().allMatch(item -> item.equals("apple")));
}

output

true
false

Fastest way to check if a value exists in a list

7 in a

Clearest and fastest way to do it.

You can also consider using a set, but constructing that set from your list may take more time than faster membership testing will save. The only way to be certain is to benchmark well. (this also depends on what operations you require)

How to check if a value in one list is in another list with a one-liner for an if statement in Python if I'm not using sets?

You can us an any(..) builtin function with a generator expression:

any(e in list2 for e in list1)

So this will check if there is at least one element that occurs in both lists.

Note however that this will result in a worst-case O(n2) algorithm. If the elements are hashable for instance, and you can use a set, we can make it an O(n) average-case algorithm.

Using any() and all() to check if a list contains one set of values or another

Generally speaking:

all and any are functions that take some iterable and return True, if

  • in the case of all(), no values in the iterable are falsy;
  • in the case of any(), at least one value is truthy.

A value x is falsy iff bool(x) == False.
A value x is truthy iff bool(x) == True.

Any non-booleans in the iterable will be fine — bool(x) will map (or coerce, if you prefer) any x according to these rules: 0, 0.0, None, [], (), [], set(), and other empty collections get mapped to False, anything else to True. The docstring for bool uses the terms 'true'/'false' for 'truthy'/'falsy', and True/False for the concrete boolean values.


In your specific code samples:

You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:

if any(foobars) == big_foobar:

...because any(foobars) would first be evaluated to either True or False, and then that boolean value would be compared to big_foobar, which generally always gives you False (unless big_foobar coincidentally happened to be the same boolean value).

Note: the iterable can be a list, but it can also be a generator/generator expression (≈ lazily evaluated/generated list) or any other iterator.

What you want instead is:

if any(x == big_foobar for x in foobars):

which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars, it compares the item to big_foobar and emits the resulting boolean into the resulting sequence:

tmp = (x == big_foobar for x in foobars)

then any walks over all items in tmp and returns True as soon as it finds the first truthy element. It's as if you did the following:

In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']                                        

In [2]: big_foobar = 'big'

In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])
Out[3]: True

Note: As DSM pointed out, any(x == y for x in xs) is equivalent to y in xs but the latter is more readable, quicker to write and runs faster.

Some examples:

In [1]: any(x > 5 for x in range(4))
Out[1]: False

In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True

In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True

In [4]: all([True, True, True, False, True])
Out[4]: False

See also: http://docs.python.org/2/library/functions.html#all



Related Topics



Leave a reply



Submit