Python logical and list

How to perform logical operations OR on list [multiple elements]?

Is there any way to compare the list elements and return the outcome value ? Below is the python snippet, where it recieves two values and returns the value.

def logical_or_decision(a,b): return a or b value = logical_or_decision(1,0) print value 

I need to make it generic & scalable to more than 2 elements.How can i do it for more than 2 elements ?

Do you want to return strictly True or False , or (in case of or ) the first truthy value of the list, as a or b or c or . would?

6 Answers 6

There’s a built-in function that does this: any .

>>> any([0,0,1,0]) True >>> any([0,0,0]) False 

what if there are 3 elements like this 0,1,-1 ? say i’ve a list of [0,-1] , it should return -1. if [0,0,-1] , it should return -1

no, only three inputs. I mean to represent three possible states, success,failure and unknown. 0, 1 , -1

@Jackie that’s not at all what the question said. Ask a new question with all information in it; editing this one would make 5 answers invalid. Include some example input/output — what you expect the function to return for some given input.

any([True, False, True]) # returns True 

any is good because «short-circuits» (like «boolean fast evaluation» it doesn’t iterate till the end).

If you want things alike but manually and eager — see reduce:

from operator import or_ from functools import reduce reduce(or_, [True, False, True]) # returns True 

any() isn’t lazy, it just short-circuits. Its laziness will depend on the iterable you have passed to it as argument.

Yes, your are quite right. I mean any is «lazy» in terms of «generator lazy evaluation» and «boolean fast evaluation» — stops at first True element — it doesn’t iterate till the end.

True, but the correct term for that is short-circuiting. Lazyness is something you would related to for example generators, they can pause their execution and would return result to you on demand not all of them at once. Here any() has no idea about the item passed to it, it just iterates over it one by one. Hence it completely depends on the iterable passed to it.

You may use reduce to do it:

def logical_or_decision(*args): return reduce( lambda a, b: a or b, args, False ) print logical_or_decision(1, 1, 1, 0) # False 

Of course you could use any or all (for logical AND ), but reduce could provide you the general way to build such operations (not for OR or AND ).

Читайте также:  Get values from java array

The builtin function any() would be the correct way to go about this:

def logical_or_decision(*args): return any(args) value = logical_or_decision(1, 0, 0, 1, 0, 0) print value 

The relevant part from the link to the official documentation above:

Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:

def any(iterable): for element in iterable: if element: return True return False 

There are two possible interpretations of the question:

1. OR & AND operations for all the elements of an iterable:

l1 = [True, False, False, True] t1 = (True, True, True) t2 = (False, False, False, False) any(l1) # True all(l1) # False any(t1) # True all(t1) # True any(t2) # False all(t2) # False 

2. OR & AND operations for multiple pairs given as two iterables:

In this case the functions used are the same but you need to use the map and zip function to wrap them:

l = [True, True, False] t = (True, False, False) list(map(any, zip(l, t))) # [True, True, False] tuple(map(all, zip(l, t))) # (True, False, False) 

NOTE: I’ve used lists and tuples to prove that it can be done with different array-like structures. The list and tuple wrapper in the second example is Python3 as map returns an iterator instead of a list and that would give a non-human-readable answer.

Источник

How to Apply Logical Operators to All List Elements in Python?

Be on the Right Side of Change

This way, you can combine an arbitrary iterable of Booleans into a single Boolean value.

Puzzle: Guess the output of this interactive code snippet—and run it to check if you were correct!

The challenge in the puzzle is to know that Python comes with implicit Boolean type conversion: every object has an associated Boolean value. Per convention, all objects are True except “empty” or “zero” objects such as [] , » , 0 , and 0.0 . Thus, the result of the function call all([True, True, 0]) is False .

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Читайте также:  Title image in html code

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

Be on the Right Side of Change 🚀

  • The world is changing exponentially. Disruptive technologies such as AI, crypto, and automation eliminate entire industries. 🤖
  • Do you feel uncertain and afraid of being replaced by machines, leaving you without money, purpose, or value? Fear not! There a way to not merely survive but thrive in this new world!
  • Finxter is here to help you stay ahead of the curve, so you can keep winning as paradigms shift.

Learning Resources 🧑‍💻

⭐ Boost your skills. Join our free email academy with daily emails teaching exponential with 1000+ tutorials on AI, data science, Python, freelancing, and Blockchain development!

Join the Finxter Academy and unlock access to premium courses 👑 to certify your skills in exponential technologies and programming.

New Finxter Tutorials:

Finxter Categories:

Источник

How to do logical and operation on list of bool objects list?

As long as you use boolean, you could zip and then use all:

data = [[True, True, True, False], [False, True, True, False], [False, False, True, True]] result = [all(e) for e in zip(*data)] print(result) 

I know, the result is the same for this particular case. But since the question asks specifically . 😉

@schwobaseggl Thanks, you are all the correct answer what I wanted. I’ve changed my question title and content to bool objects , so I choose this answer as the solution.

You can use functools.reduce and the bitwise «and» operator.and_ , as well as the typical zip(*. ) transposition pattern:

from functools import reduce from operator import and_ lst = [[True, True, True, False], [False, True, True, False], [False, False, True, True]] [reduce(and_, x) for x in zip(*lst)] # [False, False, True, False] 

It would, but it is semantically incorrect as there is no in-place update (don’t confuse reduce with in-place). Note that & and &= are two entirely different operators. Every type can overload them as they please. That, for many types, a = a & b and a &= b are equivalent, is purely conventional.

Читайте также:  Page objects selenium python

If you want to specifically use the bitwise & operator, then you can use functools.reduce with zip :

>>> from functools import reduce >>> l = [[True, True, True, False], [False, True, True, False], [False, False, True, True]] >>> [reduce(lambda x, y: x & y, lst) for lst in zip(*l)] [False, False, True, False] 

We can also create our own mini function to replace lambda :

>>> def bitwise_and(x, y): . return x & y . >>> [reduce(bitwise_and, lst) for lst in zip(*l)] [False, False, True, False] 

Or just use the operator module, as shown in @schwobaseggl’s answer.

Источник

Logical operation between two Boolean lists

I get a weird result and I try to apply the and or the or operator to 2 Boolean lists in python. I actually get the exact opposite of what I was expecting.

[True, False, False] and [True, True, False] > [True, True, False] [True, False, False] or [True, True, False] > [True, False, False] 

What I said «I actually get the exact opposite of what I was expecting». I was expecting that the first command would lead to the second result and the second command to lead to the first one.

7 Answers 7

If what you actually wanted was element-wise boolean operations between your two lists, consider using the numpy module:

>>> import numpy as np >>> a = np.array([True, False, False]) >>> b = np.array([True, True, False]) >>> a & b array([ True, False, False], dtype=bool) >>> a | b array([ True, True, False], dtype=bool) 

This is normal, because and and or actually evaluate to one of their operands. x and y is like

def and(x, y): if x: return y return x 
def or(x, y): if x: return x return y 

Since both of your lists contain values, they are both «truthy» so and evaluates to the second operand, and or evaluates to the first.

Your answer was the first correct one, thank. However I find the Davy one clearer, hence +1 but not question validation. Thanks !

I think you need something like this:

[x and y for x, y in zip([True, False, False], [True, True, False])] 

Both lists are truthy because they are non-empty.

Both and and or return the operand that decided the operation’s value.

If the left side of and is truthy, then it must evaluate the right side, because it could be falsy, which would make the entire operation false (false and anything is false). Therefore, it returns the right side.

If the left side of or is truthy, it does not need to evaluate the right side, because it already knows that the expression is true (true or anything is true). So it returns the left side.

If you wish to perform pairwise comparisons of items in the list, use a list comprehension, e.g.:

[x or y for (x, y) in zip(a, b)] # a and b are your lists 

Источник

Оцените статью