Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if list contains only item x

Tags:

python

list

Say all of w, x, y, and z can be in list A. Is there a shortcut for checking that it contains only x--eg. without negating the other variables?

w, x, y, and z are all single values (not lists, tuples, etc).

like image 622
idlackage Avatar asked Aug 31 '12 21:08

idlackage


People also ask

How do you check if a list contains only strings?

Use the filter() Function to Get a Specific String in a Python List. The filter() function filters the given iterable with the help of a function that checks whether each element satisfies some condition or not. It returns an iterator that applies the check for each of the elements in the iterable.

How do you check if a list contains a set of values?

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

How do you check if a list contains an item Python?

To check if the list contains an element in Python, use the “in” operator. The “in” operator checks if the list contains a specific item or not. It can also check if the element exists on the list or not using the list.

How do you check if a list contains a string in Python?

Python Find String in List using count() We can also use count() function to get the number of occurrences of a string in the list. If its output is 0, then it means that string is not present in the list. l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] s = 'A' count = l1.


2 Answers

A=[w,y,x,z]
all(p == x for p in A)
like image 132
gefei Avatar answered Oct 01 '22 03:10

gefei


That, or if you don't want to deal with a loop:

>>> a = [w,x,y,z]
>>> a.count(x) == len(a) and a

(and a is added to check against empty list)

like image 28
Eric Hulser Avatar answered Oct 01 '22 02:10

Eric Hulser