How to Clear an Array or List in Python
Python programming maintains a certain ease of use, partly due to how it handles data and data types. One of these data types, the list, represents a collection of data values similar to an array in other programming languages. Python comes equipped with quite a few functions that tie into lists or use lists as part of their functionality. You can also easily delete parts of a list or entire lists using built-in functions, such as the "del" function.
Instructions
-
-
1
Create a list and populate it with a few items:
>>>x = [1, 2, 3, 4, 5, 6, 7]
-
2
Delete portions of the list using the "del" keyword. This function can delete single items, or multiple items in a range:
>>>del x[0] //lists in Python are zero-indexed
>>>x
[2, 3, 4, 5, 6, 7]
>>>del x[2:4]
>>>x
[2, 3, 6, 7] -
-
3
Delete an entire list using the "del" keyword:
>>>del x
>>>x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
-
1