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.

John Bale
  • 433
  • 7
  • 16

4 Answers4

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.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
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
Nicolas
  • 5,583
  • 1
  • 25
  • 37
eumiro
  • 207,213
  • 34
  • 299
  • 261
0

The first way that comes to mind is

len([x for x in array if 3 in x[:2]]) > 0
TML
  • 12,813
  • 3
  • 38
  • 45
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
Akavall
  • 82,592
  • 51
  • 207
  • 251