0 votes
1 view
in Python by (47.8k 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 (107k 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.8k 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
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...