Reputation: 2148
I have this list :
a = [1,2,3,4,5]
I want to delete each element from the list. This is how I'm doing.
for i in range(0,len(a)):
del a[0]
Can I use list comprehension in this? such as del a[0] for i in range(0,len(a))
Upvotes: 0
Views: 155
Reputation: 280237
List comprehensions are for creating lists, not destroying them. They are not the right tool for this job.
If you want to clear the contents of a list, the quickest way is
del a[:]
This is a slice deletion. The omitted beginning and ending points default to the start and end of the list.
Note that frequently, it's better to just replace the list with a new one:
a = []
This works even if a
didn't already exist, and modifications to the new list won't interfere with any other parts of the code that needed the old list. These attributes are often, though not always, desirable.
Upvotes: 4
Reputation: 1009
List comprehension (coming from functional programming, where nothing is ever mutated) is for building lists. Since it appears you want to clear out the elements of an existing list (and not creating a new list with only some of the elements etc.), list comprehension is not the right tool.
That said, list comprehension can be abused to do it:
[a.pop() for i in range(len(a))]
NOTE: This is a bad idea (since it uses list comprehenstion for something completely different than what it is intended for) and I would strongly recommend you do not use it.
Upvotes: 1
Reputation: 91017
No, you cannot del
components in a list comprehension. Why would you want to do that in the first place? A list comprehension is for creating a list, not for modifying.
You can replace the list with a different one created with a list comprehension.
The reason is that a list comprehension needs an expression. But del
is a statement.
Upvotes: 1
Reputation: 599490
You wouldn't usually do this with a loop at all. To clear an existing list, use a[:] = []
.
Upvotes: 3