Erase whole array Python

Question:

How do I erase a whole array, leaving it with no items?

I want to do this so I can store new values in it (a new set of 100 floats) 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.

Asked By: pjehyun

||

Answers:

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.

Answered By: David Z

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.

Answered By: Matthew Flaschen

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]

Answered By: John Machin

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'))
Answered By: John Machin

Python List clear() Method
The clear() method removes all the elements from a list.

fruits = ['apple', 'banana', 'cherry', 'orange']
fruits.clear()
print(fruits)
# outputs: []
Answered By: FFish
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.