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
  • 435
  • 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
  • 203,151
  • 43
  • 392
  • 509
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,265
  • 1
  • 23
  • 37
eumiro
  • 194,053
  • 32
  • 286
  • 259
0

The first way that comes to mind is

len([x for x in array if 3 in x[:2]]) > 0
TML
  • 12,394
  • 3
  • 36
  • 43
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
  • 76,296
  • 45
  • 192
  • 242