views:

98

answers:

4

Hey guys, how would you erase a whole array, as in it has no items. I want to do this so I could store new values (a new set of 100 floats) into it and find the minimum.

Right now my program is reading the minimum from sets before I think because it is appending itself with the previous set still in there (i use .append by the way).

+4  A: 

It's simple:

array = []

will set array to be an empty list. (They're called lists in Python, by the way, not arrays)

If that doesn't work for you, edit your question to include a code sample that demonstrates your problem.

David Zaslavsky
haha wow thanks
pjehyun
+7  A: 

Note that list and array are different classes. You can do:

del mylist[:]

This will actually modify your existing list. David's answer creates a new list and assigns it to the same variable. Which you want depends on the situation (e.g. does any other variable have a reference to the same list?).

Try:

a = [1,2]
b = a
a = []

and

a = [1,2]
b = a
del a[:]

Print a and b each time to see the difference.

Matthew Flaschen
+1 Heh we wrote almost exactly the same, but you were first.
Mark Byers
Really, there are arrays in Python? I did not know that. (Actually I probably knew but forgot) Anyway +1 for expanding on the difference between our answers. I just made a guess that the difference wouldn't matter for the OP.
David Zaslavsky
i see. that helps@david: yah, there's not much difference for me. but my newbness has gotten lessened :P
pjehyun
@Matthew Flaschen: "arrays are different": not really, `del` works; see my answer
John Machin
@John, I didn't mean `del` wouldn't work, just that lists and arrays are different.
Matthew Flaschen
A: 

Well yes arrays do exist, and no they're not different to lists when it comes to things like del and append:

>>> from array import array
>>> foo = array('i', range(5))
>>> foo
array('i', [0, 1, 2, 3, 4])
>>> del foo[:]
>>> foo
array('i')
>>> foo.append(42)
>>> foo
array('i', [42])
>>>

Differences worth noting: you need to specify the type when creating the array, and you save storage at the expense of extra time converting between the C type and the Python type when you do arr[i] = expression or arr.append(expression), and lvalue = arr[i]

John Machin
+1  A: 

Now to answer the question that perhaps you should have asked, like "I'm getting 100 floats form somewhere; do I need to put them in an array or list before I find the minimum?"

Answer: No, if somewhere is a iterable, instead of doing this:

temp = []
for x in somewhere:
   temp.append(x)
answer = min(temp)

you can do this:

answer = min(somewhere)

Example:

answer = min(float(line) for line in open('floats.txt'))
John Machin