idlackage
idlackage

Reputation: 2863

Check if list contains only item x

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

Answers (9)

Joe
Joe

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

Eric Hulser
Eric Hulser

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

the wolf
the wolf

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

Samy Vilar
Samy Vilar

Reputation: 11100

Heres another way:

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

of the many already stated.

Upvotes: 1

Claudiu
Claudiu

Reputation: 229301

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

all(element==x for element in A)

Upvotes: 5

gefei
gefei

Reputation: 19766

A=[w,y,x,z]
all(p == x for p in A)

Upvotes: 37

Oleksii Kachaiev
Oleksii Kachaiev

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

Chinmay Kanchi
Chinmay Kanchi

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

David Robinson
David Robinson

Reputation: 78590

If all items in the list are hashable:

set(A) == set([x])

Upvotes: 5

Related Questions