1

Is it possible somehow to preform logical functions on arrays like eg.

a= [1,2,3,4,5,6]
b= [1,3,5,7]
c= a and b

resulting in c=[1,3,5]

so only the values that are present in both the arrays.

The same with or eg:

d = a OR b 

resulting in b=[1,2,3,4,5,6,7]

Is this possible somehow in python or are there short functions for this? Thanks for your response

2
  • 3
    look at sets Commented Mar 31, 2021 at 8:19
  • This is possible when you convert your arrays to numpy arrays. Checkout Numpy Logic Functions Commented Mar 31, 2021 at 8:21

3 Answers 3

1

Lists do not support logical operations , but you can do it in sets:

a= [1,2,3,4,5,6]
b= [1,3,5,7]

c = list(set(a) | set(b))

d = list(set(a) & set(b))

print(c)
# OUTPUT: [1, 2, 3, 4, 5, 6, 7]
print(d)
# OUTPUT: [1, 3, 5]
Sign up to request clarification or add additional context in comments.

Comments

0

You probably should use python set if your collections contain unique values. They are actually mathematical sets: https://en.wikipedia.org/wiki/Set_(mathematics) and support general operation for sets such as intersection and union

>>> a = {1, 2, 3, 4, 5, 6}
>>> b = {1, 3, 5, 7}
>>> c = a.intersection(b)
>>> c
{1, 3, 5}

1 Comment

Thank you, this would work as well c=set(a).intersection(set(b)) or d=set(a).union(set(b)) Since I get my arrays from an other function I can convert first. Also a nice way of doing it.
0

Here is your snippet:

def and_array(a, b):
    return [a[i] for i in range(min(len(a), len(b))) if a[i] in b or b[i] in a]
def or_array(a, b):
    return a + [element for element in b if not element in a]
    
a= [1,2,3,4,5,6]
b= [1,3,5,7]
c = and_array(a, b)
d = or_array(a, b)
print(c)
print(d)

Result:

[1, 2, 3]
[1, 2, 3, 4, 5, 6, 7]

It is not that fast, avoid this for very large lists and use numpy or build-in functions!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.