Reputation: 9
I want to write a condition that check if the list has another string that is not '1'
or '2'
.
For example:
list = ['1', '2'] -> is True
list = ['1', '3'] -> is false
I tried something like that but it didn't work:
if list[0] is not '1' or list[0] is not '2' and list[1] is not '1' or list[1] is not '2':
return False
else:
return True
Help someone??
Upvotes: 0
Views: 930
Reputation: 135
For starters, welcome! :)
We can try the all() function to check all the elements in the list using if statements (making it a little easier to read):
For example:
list1 = ['1', '3']
if all(elem in ('1', '2') for elem in list1): #if all elements in the list have '1' or '2'
True #return true
else: #if not
False #return false
Output:
False
Hope this is what you were looking for.
Upvotes: 0
Reputation: 36
Hellooooo!! First thing u can do is to make an iter object.
s=iter("12")
This will create an iter object with "1" and "2".You must be thinking why to use iter rather than a list. The answer lies in the size,memory of iter objects is less than that of list.
import sys
l=["1","2"]
s=iter("12")
sys.getsizeof(l) #return 72
sys.getsizeof(s) #return 48
So what i did was that,i got the memory size of l and s. If you want to know more about this function,then go to sys.getsizof() Now coming back to your question,check the code below.
for element in l:
if element in s:
print("69 is not just a number!!!") #You can replace this part by anything u want
Output:
69 is not just a number!!!
69 is not just a number!!!
The benefit of this is that you can use this for much more strings!!!.And the memory will be very less.
You can also do it how Austin did it.
Keep Learning!
Upvotes: 0
Reputation: 1057
Try something like this,
l1=['1','2']
l2=['1','3']
def check(l1):
if '1' in l1 and '2' in l1:
print('True')
else:
print('False')
check(l1)
check(l2)
output:
True
False
Upvotes: -1
Reputation: 134
Don't use list
as variable since it is a built-in function.
checking_elements = ['1', '2']
ls = ['1', '3']
for ele in ls:
if ele not in checking_elements:
return False
return True
if your ls
is going to be only two elements.Then
checking_elements = ['1', '2']
ls = ['1', '3']
return (ls[0] in checking_elements and ls[1] in checking_elements)
Upvotes: 0
Reputation: 1907
You can use any()
for this, simply pythonic:
def check_list(l):
return not any(x not in ('1', '2') for x in l)
Upvotes: 1
Reputation: 26039
Use all
in a generator:
def check_value(lst):
return all(x in ('1', '2') for x in lst)
Usage:
>>> check_value(['1', '2'])
True
>>> check_value(['1', '3'])
False
Upvotes: 2