Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

It seems so "dirty" emptying a list in this way:

while len(alist) > 0 : alist.pop()

Does a clear way exist to do that?

1 Answer

0 votes
by (106k points)

There are many ways to empty a list in Python some of the important ways I am mentioning here:-

The first method you can use is the del lst[:] method this method will remove the contents from the list, but it will not replace the old label with a new empty list.

An example that shows how to use the above del lst[:] method:-

lst1 = [1, 2, 3]

del lst1[:]

print(lst1)

image

The other way of doing this problem if you're running Python 3 is to use the clear() method:-

alist = [1, 2, 3]

alist.clear() 

print(alist)

image

Related questions

0 votes
1 answer
asked Aug 24, 2019 in Python by Sammy (47.6k points)
0 votes
2 answers
asked May 30, 2019 in Python by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...