Search code examples
pythonarrayslistnumpyminimum

Issue obtaining minimum value of list/array


I'm having a weird issue, at least I can't explain the reason for this behaviour.

I generate a list of random values with the function rand_data as defined below. When I attempt to extract the minimum value using the min() function, it returns the whole list, which leads me to believe it is not a list but an array.

But if I attempt to use the .min() attribute it returns the error:

AttributeError: 'list' object has no attribute 'min'

What is happening here? Is x1 a list or an array?

Minimal working example:

import numpy as np

def rand_data():
    return np.random.uniform(low=10., high=20., size=(10,))

# Generate data.
x1 = [rand_data() for i in range(1)]

print min(x1)
print x1.min()

Solution

  • You used a list comprehension:

    x1 = [rand_data() for i in range(1)]
    

    You now have a Python list object containing one result from rand_data().

    Since rand_data() uses numpy.random.uniform() that means you have a list containing a numpy array.

    Don't use a list comprehension here, it is clearly not what you wanted:

    x1 = rand_data()