Clear an array in python

Erase whole array Python

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.

5 Answers 5

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

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?).

Print a and b each time to see the difference.

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.

i see. that helps @david: yah, there’s not much difference for me. but my newbness has gotten lessened 😛

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

Читайте также:  Python dictionary добавить пару

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

This is how you re-initialize array if you are doing in a loop. This is fundamentally the right answer to the OP’s question.

I prefer this approach as coming from a VBA background we use array = («») so very similar and easy to rememeber! +1

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]

Источник

Метод clear() в Python

Метод не принимает никаких параметров. clear() очищает только указанный список. Он не возвращает никакого значения.

Пример 1

# Defining a list list = [, ('a'), ['1.1', '2.2']] # clearing the list list.clear() print('List:', list)

Примечание. Если вы используете Python 2 или Python 3.2 и ниже, вы не можете использовать метод clear(). Вместо этого вы можете использовать оператор del.

Пример 2: Очистка списка с помощью del

# Defining a list list = [, ('a'), ['1.1', '2.2']] # clearing the list del list[:] print('List:', list)

Параметры

clear() в Python не принимает никаких параметров.

Возвращаемое значение

Метод не возвращает никакого значения (не возвращает None).

Пример 1: Как метод работает со словарями?

Очистка списка на месте повлияет на все остальные ссылки того же списка.

Например, этот метод не влияет на другие ссылки:

>>> a = [1, 2, 3] >>> b = a >>> a = [] >>> print(a) [] >>> print(b) [1, 2, 3]
>>> a = [1, 2, 3] >>> b = a >>> del a[:] # equivalent to del a[0:len(a)] >>> print(a) [] >>> print(b) [] >>> a is b True

Также можно сделать так
>>> a[:] = []
Выполнение alist = [] не очищает список, а просто создает пустой список и привязывает его к переменной alist. Старый список все еще будет существовать, если у него были другие привязки переменных.

Чтобы действительно очистить список, вы можете использовать любой из этих способов:
alist.clear() # Python 3.3+, most obvious
del alist[:]
alist[:] = []
alist *= 0 # fastest
Существует очень простой способ очистить список python. Использовать del list_name[:].

Например:
>>> a = [1, 2, 3]
>>> b = a
>>> del a[:]
>>> print a, b
[] []
Также этот код
del old_list[ 0:len(old_list) ]
эквивалентен
del old_list[:]
del list[:]
Удалит значения этой переменной списка

del list
Удалит саму переменную из памяти.
В случае, если вам список снова понадобится, вы можете повторно инициализировать его. Или просто очистить его элементы с помощью
del a[:]

Источник

How to clear an Array in Python?

I am trying to create an array and then clear it using a function, but the terminal keeps displaying ‘list index out of range’.

duplicates = [] def ClearArray(): for index in range(100): duplicates[index].append("") ClearArray() print(duplicates) 

The instruction is to Initialise the global array Duplicates, which is a 1D array of 100 elements of data type STRING, and set all elements to empty string using a function.

Maybe you want to initialize a list of lists duplicates = [[]]*100 or a list of empty strings [«» for _ in range(100)] ? It is really unclear what the «array» is.

You have a size zero list and are attempting to access, a 1 through 100 position which doesnt exist, ofc it gives you index out of range. If you want to clear is simply redeclare is as an empty list, or if you want a 100 empty member, then do duplicates.append(«»)

4 Answers 4

You are getting the error because you are initializing an empty list and then trying to access elements inside of that list.

In the first iteration of the for loop, you attempt to access duplicates[0] but the list is empty, and therefore the list index out of range exception is raised. You can resolve this by replacing duplicates[index].append(«») with duplicates.append(«») .

You can read more about python lists here.

In addition, according to python’s PEP8 function names should be lowercase, with words separated by underscores as necessary to improve readability.

duplicates = [] def clear_array(): for index in range(100): duplicates.append("") clear_array() print(duplicates) 

To remove all elements of a list, you can use clear , like so:

Источник

4 Ways to Clear a Python List

Python Clear List Cover Image

In this tutorial, you’ll learn four different ways to use Python to clear a list. You’ll learn how to use the clear method, the del statement, the *= operator, and list item re-assignment. Knowing how to clear a list is a task that should seem easy, but is an often elusive skill. After reading this tutorial, you’ll have learned four different ways to clear a Python list in order to start fresh.

The Quick Answer: Use clear

Quick Answer - Python Clear List

What are Python Lists?

Lists in Python are one of the main data structures that exist in the language. They have some unique attributes, similar to arrays in other languages. They can hold values of different data types, meaning that they’re heterogeneous. They are also ordered, meaning that you can access the items by their index position. Python list indices start at 0 and increment by 1. Python lists can also contain duplicate values.

How does Python List Indexing Work

In the next section, you’ll learn how to clear a Python list with the .clear() method.

Clear a Python List with Clear

One of the easiest ways to clear a Python list is to the use the list.clear() method. The method empties a given list and doesn’t return any items. The method was introduced in Python 3.2, so if you’re using an earlier version, you’ll need to read on to learn how to use the del operator.

Let’s see how we can empty a list by using the clear method:

# Clear a Python List with .clear() items = ['datagy', 1, 2, 3] items.clear() print(items) # Returns: []

Let’s break down what we did above:

  1. We instantiated a list
  2. We then applied the clear method to empty the list
  3. We print the list to ensure that the list is emptied

Now that we know how to use the clear method, we can explore some additional properties about it. The method doesn’t accept any arguments and it modifies a list in place (meaning that we don’t re-assign it to another list).

In the next section, you’ll learn how to empty a Python list with the del keyword.

Want to learn how to pretty print a JSON file using Python? Learn three different methods to accomplish this using this in-depth tutorial here.

Clear a Python List with del

The Python del keyword allows us to delete a particular list item or a range of list items at particular indices. If you want to learn how to use the Python del keyword to delete list items, check out my in-depth tutorial here. Since we can use the Python del keyword to delete items or ranges of items in a list, we can simply delete all items in the list using the : operator.

Let’s see how we can use the del keyword to empty a Python list:

# Clear a Python List with del items = ['datagy', 1, 2, 3] del items[:] print(items) # Returns: []

Let’s break down what we did here:

  1. We instantiated a Python list, items
  2. We then used the del keyword to delete items from the first to the last index
  3. We then printed the list to make sure it was empty

Interestingly, the .clear() method works exactly the same as the del [:] keyword, under the hood. It really just represents syntactical sugar in order to make the process a little easier to understand.

In the next section, you’ll learn how to empty a Python list using the *= operator.

Want to learn more about Python f-strings? Check out my in-depth tutorial, which includes a step-by-step video to master Python f-strings!

Clear a Python List with the *= Operator

Python allows us to chain operators together. For example, writing a = a + 1 is the same as writing a += 1 . Another way to chain operators is to use the *= , which reassigns the variable multiplied by zero. When we apply this operator a list, we assign the value of 0 to each item, thereby removing the items from the list.

Let’s see how we can use the *= operator to empty a Python list of all of its elements:

# Clear a Python List with *= items = ['datagy', 1, 2, 3] items *= 0 print(items) # Returns: []

In the next section, you’ll learn how to use Python to empty a list using list item re-assignment.

Want to learn how to use the Python zip() function to iterate over two lists? This tutorial teaches you exactly what the zip() function does and shows you some creative ways to use the function.

Clear a Python List with List Item Re-assignment

While it may seem intuitive to empty a list simply by writing some_list = [] . This approach doesn’t actually delete the items from the list, it just removes the reference to the items. If the list has also been assigned to another variable, it’ll be retained in memory.

We can, however, assign the full range of items to be empty items. This will delete all of the items in a list, thereby clearing it.

Let’s see how we can do this with Python:

# Clear a Python List with *= items = ['datagy', 1, 2, 3] items[:] = [] print(items) # Returns: []

In the example above, we can see that we re-assigned all of the list items by using the list indexing method. We were able to access all of the items and assign them an empty value.

Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.

Conclusion

In this tutorial, you learned four different ways to use Python to clear a list. You learned how to use the .clear() method, the del keyword, the *= operator, and list item re-assignment. Being able to work with lists in different ways is an important skill for a Pythonista of any level.

To learn more about Python lists, check out the official documentation here.

Источник

Оцените статью