I am using Python 3.x.
If I want to see if there are 8 numbers in any of three lists how would I do that in Python.
If I have:
list1 = [5, 6, 7, 2, 3, 5]
list2 = [2, 5, 8, 9, 1, 5]
list3 = [4, 6, 7 ,9, 2, 3]
How would I write this correctly in python?:
if 5 and 6 and 3 in (lists 1, 2, and 3)
The part in parenthesis is obviously not correct. How would I write the correct syntax for this in Python?
This is pretty simple and quite obvious to do. If you want to check if any number is in any list, you do this:
If you want to check that all numbers are in all lists, you do this:
If you want to check for all numbers in any lists, it gets more complicated. The easiest and clearer is to have two methods:
And you’d use the functions above like this:
Since you want less code, there are various “shortcuts” you can use. The shortcuts can make the code shorter, but will also make it less clear and harder to read, and hence they are not really a better choice. For example you can use the any function, and a generator expression:
You can even nest two of them:
But understanding that code takes a long time and much more brain power. It is also significantly slower, as it will go through all lists, even if it finds a match in the first one. I can’t think of any way that is not slower at the moment, but there may be one. But you are unlikely to find anything that is significantly faster and not significantly more confusing.
For the case of checking that all numbers are in all lists, you would do this:
Which also, for some reason takes twice the time compared with the function above, even though there will be no shortcuts. It may have to do with the creation of intermediary lists.
This is often the case with Python: Simple is best.
Line by line explanation of the code you used, since you asked for it:
Defines a function, called “all_numbers_in_list”, with the parameters “l” and “numbers”.
For every item in numbers, assign variable “n” to that number, and then do the following block.
If the value of variable “n” is not in the list “l”.
Exit the function with False as return value.
Exit the function with True as return value.
Defines a function, called “all_numbers_in_any_list”, with the parameters “lists” and “numbers”.
For every item in lists, assign variable “l” to that number, and then do the following block.
If calling the function “all_numbers_in_list” with the parameters “l” and “numbers” return True, do the following block:
Exit the function with True as return value.
Exit the function with False as return value.
Did that help?