2
aBool = bool(aList.index(aVal))

I tried this but it gives an error for false. Any help is appreciated!

  • 1
    Possible duplicate: http://stackoverflow.com/questions/7571635/fastest-way-to-check-if-a-value-exist-in-a-list – sgp May 29 '15 at 04:44
  • hi @Neil always make your question simple and show what problems you get and what steps you have taken and all .Follow this [link](http://stackoverflow.com/help/how-to-ask) for more details – The6thSense May 29 '15 at 04:48

5 Answers5

2
aVal in aList

The in operator does what you need, if I understand correctly.

fiacre
  • 1,150
  • 2
  • 9
  • 26
1
aList = [10, 20, 30, 40, 50]
aVal = 50
bool = aVal in aList
print bool
Uma Kanth
  • 5,659
  • 2
  • 20
  • 41
1

There are different ways you could approach this problem but the easiest would be to use a conditional with the 'in' operator. For example,

#testbool will hold your boolean value
#testlist will be your list
#testvar will be your variable you are checking the list for

if testvar in testlist:
    testbool = true
else:
    testbool = false
  • I warmly suggest you to simplify your code to: `testbool = testvar in testlist`. There is no need for an `if ... else` statement. – davidedb May 30 '15 at 10:47
1

Here's a general solution to it:

_list = range(10)
aVal = 7
aBool = (lambda val, l: True if val in l else False)(aVal, _list)
print(aBool)

You can pass any value to the first argument, and any list to the second argument, and it'll always return True if the value is inside the given list (And just like you want, return False if otherwise).

Ericson Willians
  • 7,606
  • 11
  • 63
  • 114
  • Please, always try to keep your code simple ([KISS](http://en.wikipedia.org/wiki/KISS_principle))! What is the added value compared to `aBool = aVal in _list`? What do you mean with _general solution_? – davidedb May 30 '15 at 10:52
0

Use testvar in testlist will return a boolean value.

If you want to reuse the value, you can do as below:

aTest = aVal in aList
Burger King
  • 2,945
  • 3
  • 20
  • 45