Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy.Array in Python list?

Tags:

python

numpy

I've got a list (used as a stack) of numpy arrays. Now I want to check if an array is already in the list. Had it been tuples for instance, I would simply have written something equivalent to (1,1) in [(1,1),(2,2)]. However, this does not work for numpy arrays; np.array([1,1]) in [np.array([1,1]), np.array([2,2])] is an error (ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()). The error message does not help here AFAIK, as it is referring to comparing arrays directly.

I have a hard time beliving it wouldn't be possible, but I suppose there's something I'm missing.

like image 920
carlpett Avatar asked Mar 30 '11 15:03

carlpett


People also ask

Can NumPy array contain list?

The most import data structure for scientific computing in Python is the NumPy array. NumPy arrays are used to store lists of numerical data and to represent vectors, matrices, and even tensors.

What is the difference between NumPy array and Python list?

NumPy & Lists Originally known as 'Numeric,' NumPy sets the framework for many data science libraries like SciPy, Scikit-Learn, Panda, and more. While Python lists store a collection of ordered, alterable data objects, NumPy arrays only store a single type of object.

How do I make a list an array in Python?

To convert a list to array in Python, use the np. array() method. The np. array() is a numpy library function that takes a list as an argument and returns an array containing all the list elements.


3 Answers

To test if an array equal to a is contained in the list my_list, use

any((a == x).all() for x in my_list)
like image 94
Sven Marnach Avatar answered Oct 23 '22 22:10

Sven Marnach


If you are looking for the exact same instance of an array in the stack regardless of whether the data is the same, then you need to this:

id(a) in map(id, my_list)
like image 29
Paul Avatar answered Oct 23 '22 21:10

Paul


Sven's answer is the right choice if you want to compare the actual content of the arrays. If you only want to check if the same instance is contained in the list you can use

any(a is x for x in mylist)

One benefit is that this will work for all kinds of objects.

like image 45
andrenarchy Avatar answered Oct 23 '22 21:10

andrenarchy