0

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()
5
  • an array is a list in python Commented Jul 13, 2014 at 0:28
  • 2
    You have a list object, containing the results of 1 rand_data() call. Commented Jul 13, 2014 at 0:28
  • 1
    You're generating a list with one element in it and that element is an array Commented Jul 13, 2014 at 0:28
  • @GoBrewers14 ohh that's an easy explanation. Would you mind posting it as an answer? Commented Jul 13, 2014 at 0:30
  • Nevermind, I see @MartijnPieters just posted that exact answer. Commented Jul 13, 2014 at 0:31

2 Answers 2

3

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()
Sign up to request clarification or add additional context in comments.

1 Comment

I get it now. I was using that method to generate several lists of random data, hence the [rand_data() for i in range(1)]. Thank you!
0
import numpy as np

def rand_data(num_elements):
# numpy returns always an array with a defined number
# of elements specified by the size parameter
     return np.random.uniform(low=10., high=20., size=num_elements)

#rand_data will automatically generate the random data for you
# simply specifying the number of elements to generate
x1 = rand_data(10)

print('Minimum value for {0} is {1}'.format(x1, min(x1)))

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.