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).
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).
A=[w,y,x,z]
all(p == x for p in A)
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)
This checks that all element
s in A
are equal to x
without reference to any other variables:
all(element==x for element in A)
If all items in the list are hashable:
set(A) == set([x])
{x} == {w,x,y,z} & set(A)
This will work if all of [w,x,y,z]
and items in A
are hashable.
I'm not sure what without negating the other variables means, but I suspect that this is what you want:
if all(item == x for item in myList):
#do stuff
There are two interpretations to this question:
First, is the value of x contained in [w,y,z]:
>>> w,x,y,z=1,2,3,2
>>> any(x == v for v in [w,y,z])
True
>>> w,x,y,z=1,2,3,4
>>> any(x == v for v in [w,y,z])
False
Or it could mean that they represent the same object:
>>> w,x,y,z=1,2,3,4
>>> any(x is v for v in [w,y,z])
False
>>> w,x,y,z=1,2,3,x
>>> any(x is v for v in [w,y,z])
True
Yet another approach that works for a list with hashable items and also handles empty lists.
len(set(A)) == 1
Not sure if this is the most efficient solution, but I think it is quite readable and scores well at Code Golf :)
Some examples:
A = [1, 1, 1, 1]
len(set(A)) == 1
>>> True
A = [1, 2, 3, 4]
len(set(A)) == 1
>>> False
A = []
len(set(A)) == 1
>>> False
A = [(1,), (1,), (1,), (1,)]
len(set(A)) == 1
>>> True
A = [[1,], [1,], [1,], [1,]]
len(set(A)) == 1
TypeError: unhashable type: 'list'