2

I have an array with each index being another array. If I have an int, how can I write code to check whether the int is present within the first 2 indicies of each array element within the array in python.

eg: 3 in

array = [[1,2,3], [4,5,6]] 

would produce False.

3 in

array = [[1,3,7], [4,5,6]] 

would produce True.

4 Answers 4

5

You can slice your array to get a part of it, and then use in operator and any() function like this:

>>> array = [[1,2,3], [4,5,6]]
>>> [3 in elem[:2] for elem in array]
[False, False]
>>> any(3 in elem[:2] for elem in array)
False

>>> array = [[1,3,7], [4,5,6]]
>>> [3 in elem[:2] for elem in array]
[True, False]
>>> any(3 in elem[:2] for elem in array)
True

any() function returns True if at least one of the elements in the iterable is True.

Sign up to request clarification or add additional context in comments.

Comments

3
>>> a = [[1,2,3], [4,5,6]]
>>> print any(3 in b[:2] for b in a)
False

>>> a = [[1,3,7], [4,5,6]] 
>>> print any(3 in b[:2] for b in a)
True

Comments

0

The first way that comes to mind is

len([x for x in array if 3 in x[:2]]) > 0

Comments

0

You can use numpy.array

import numpy as np

a1 = np.array([[1,2,3], [4,5,6]]) 
a2 = np.array([[1,3,7], [4,5,6]])

You can do:

>>> a1[:, :2]
array([[1, 2],
       [4, 5]])
>>> 3 in a1[:, :2]
False
>>> 3 in a2[:, :2]
True

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.