17

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).

idlackage
  • 2,595
  • 8
  • 28
  • 46

8 Answers8

31
A=[w,y,x,z]
all(p == x for p in A)
gefei
  • 18,124
  • 7
  • 49
  • 65
  • 3
    Be careful: if list is empty, the expression always evaluates to `True`- although `x` is not in the list. If the list may be empty, use `all(p == x for p in A) and len(A) > 0` – Mesa Aug 24 '18 at 12:27
  • Would be helpful if you could make in an example with both Lists, I can't understand that code at all – eliezra236 Nov 07 '21 at 18:57
20

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)

Jean-François Fabre
  • 131,796
  • 23
  • 122
  • 195
Eric Hulser
  • 3,794
  • 19
  • 20
4

This checks that all elements in A are equal to x without reference to any other variables:

all(element==x for element in A)
Claudiu
  • 216,039
  • 159
  • 467
  • 667
4

If all items in the list are hashable:

set(A) == set([x])
David Robinson
  • 74,512
  • 15
  • 159
  • 179
4
{x} == {w,x,y,z} & set(A)

This will work if all of [w,x,y,z] and items in A are hashable.

Alexey Kachayev
  • 5,956
  • 26
  • 24
1

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
Chinmay Kanchi
  • 58,811
  • 22
  • 84
  • 113
1

Heres another way:

>>> [x] * 4 == [x,w,z,y]

of the many already stated.

Samy Vilar
  • 10,109
  • 2
  • 34
  • 33
0

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
the wolf
  • 32,251
  • 12
  • 52
  • 71