19

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,715
  • 8
  • 31
  • 52

9 Answers9

34
A=[w,y,x,z]
all(p == x for p in A)
gefei
  • 18,922
  • 9
  • 50
  • 67
  • 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
21

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
  • 137,073
  • 23
  • 153
  • 219
Eric Hulser
  • 3,912
  • 21
  • 20
5

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
  • 224,032
  • 165
  • 485
  • 680
5

If all items in the list are hashable:

set(A) == set([x])
David Robinson
  • 77,383
  • 16
  • 167
  • 187
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
  • 6,106
  • 27
  • 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
  • 62,729
  • 22
  • 87
  • 114
1

Heres another way:

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

of the many already stated.

Samy Vilar
  • 10,800
  • 2
  • 39
  • 34
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
  • 34,510
  • 13
  • 53
  • 71
0

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'
Joe
  • 6,758
  • 2
  • 26
  • 47