Best Way to Clear a List in Python


Have you ever wondered that which is the best way to clear off a list in python? Probably yes, as there are so many ways to do it. In this article, we will be discussing the difference between list = [] and list.clear() in python. These are used to clear entries in list in Python

An example of list.clear() :

>>> l1 = [1, 2, 3] >>>l2 = l1 >>>l1.clear() l1 # is empty and so is l2

An example of list = [] :

>>> l1 = [1, 2, 3] >>>l2 = l1 >>>l1 = [] >>>l1 # is empty >>>l2 # still points to previous

There are few other ways to clear a list in place in Python, these are:

list.clear() list[:] = [] list *= 0 Del list[:]

Solution Worked 0 UpvotesUpvote


Solution Didn't Worked 0 DownvotesDownvote


Get Programming Help

Play 2048 Game Online

Search Tags