Reputation: 2863
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).
Upvotes: 22
Views: 35898
Reputation: 7121
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'
Upvotes: 0
Reputation: 4022
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)
Upvotes: 22
Reputation: 35522
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
Upvotes: 0
Reputation: 11100
Heres another way:
>>> [x] * 4 == [x,w,z,y]
of the many already stated.
Upvotes: 1
Reputation: 229301
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)
Upvotes: 5
Reputation: 6234
{x} == {w,x,y,z} & set(A)
This will work if all of [w,x,y,z]
and items in A
are hashable.
Upvotes: 4
Reputation: 65853
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
Upvotes: 1