Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python List clear()

#1
Python List clear()

Surprisingly, even advanced Python coders don’t know about the clear() method of Python lists. Time to change that!

Definition and Usage: The list.clear() method removes all elements from an existing list. The list becomes empty again.

Here’s a short example:

>>> lst = [1, 2, 3, 4, 5]
>>> lst.clear()
>>> lst
[]

In the first line, you create the list lst consisting of five integers. You then remove all elements from the list. The result is the empty list.

Puzzle – Try It Yourself:

Syntax: You can call this method on each list object in Python. Here’s the syntax:

list.clear()

Arguments: The method doesn’t take any argument.

Return value: The method list.clear() has return value None. It operates on an existing list and, therefore, doesn’t return a new list with the removed element

Video:



Python List clear() vs New List


Now, if you’re an alert reader, you may ask the following interesting question: why to use the clear() method in the first place when you also can simply create a new list and be done with it?

Here’s an example where both ways lead to the same result:

>>> lst = [1, 2, 3]
>>> lst.clear()
>>> lst
[]
>>> lst = [1, 2, 3]
>>> lst = []
>>> lst
[]

I know the code seems to be a bit odd but it shows that instead of clearing an existing list, you can also create a new list. In this case, this leads to the exact same result.

However, Python is an object-oriented language. And if you just create a new object and assign it to a variable, the original list still exists in memory. And other variables may point to the object.

Consider the following code snippet that exemplifies this:

lst = [1, 2, 3]
lst_2 = lst
lst = []
print(lst_2)
# [1, 2, 3]

I’ve created a Python visualization for you so that you can see the objects in memory:


Simply assigning a new list to the variable lst will leave the other variable lst_2 unaffected. Instead, you should have used lst.clear() to make sure that both variables now point to the same empty list object.

lst = [1, 2, 3]
lst_2 = lst
lst.clear()
print(lst_2)
# []

Python List clear() Memory


The effect of the clear() method is that the list is now empty.

In theory, you released the Python virtual machine from the burden of keeping the elements in the memory. Python uses reference counting to determine if some elements in the memory are not referenced anymore (and, thus, can be considered unused). Those elements will be removed—we say, they are deallocated from memory. If you clear the list, you essentially remove all references from the list to the list elements. However, some old list elements may still be referenced from the outside (e.g. by another variable). So they are not necessarily removed because they may still be needed! Just keep this in mind when clearing the list.

In practice, however, even referenced elements may still exist in the memory until the Python garbage collector (or even the operating system) removes the elements from memory.

Python List clear() Complexity


The runtime complexity of list.clear() is O(n) for a list with n elements. Why? Well, you first need to understand what happens if you remove all elements from a list. The list elements are not physically (or, for that matter, digitally) stored in the list. The list contains only references to the real list element objects in memory. If you clear the list, you remove all those references.

The garbage collector in Python goes over all elements in the memory to remove the ones that have a reference count of zero. Why? Because they are the ones that cannot be accessed in the code. Thus, the garbage collector can safely assume that they are unused and are not needed anymore. As you see, the garbage collector needs the reference count information for each element in memory.

The algorithm when clearing a list is simple: reduce the reference count of each list element object by one. The objects that end up with reference count zero can now be removed from memory. But as you need to go over all list elements, the runtime complexity is linear to the list size.

Python List clear() Not Working


The Python list.clear() method was added in Python 3.3 (official source). So if you try to use it for any Python version before that, you must use the del list[:] method that is semantically equivalent and works for earlier Python versions, too.

Related articles on the Finxter blog:

Python List clear() Version 2.7


Have you tried to use Python list.clear() in Python 2.7? It’s not possible. The clear() method was added in Python 3.3 (official source). So if you try to use it for any Python version before that (including 2.7), you must use the del list[:] method that is semantically equivalent and works for earlier Python versions, too.

Related articles on the Finxter blog:

Python List clear() vs del


You may ask: what’s the difference between the list.clear() method and the del operation?

The answer is simple: there isn’t any semantic difference. The list.clear() method is just syntactical sugar for del list[:] (source).

Here’s an example demonstrating that both are, in fact, the same:

>>> lst = [1, 2, 3]
>>> lst.clear()
>>> lst
[]
>>> lst = [1, 2, 3]
>>> del lst[:]
>>> lst
[]

List Removal Alternatives


There are some alternative list methods to remove elements from the list. See the overview table:


Method Description
lst.remove(x) Remove an element from the list (by value)
lst.pop() Remove an element from the list (by index) and return the element
lst.clear() Remove all elements from the list
del lst[3] Remove one or more elements from the list (by index or slice)
List comprehension Remove all elements that meet a certain condition

Python List clear() Thread Safe


Do you have a multiple threads that access your list at the same time? Then you need to be sure that the list operations (such as clear()) are actually thread safe.

In other words: can you call the clear() operation in two threads on the same list at the same time? (And can you be sure that the result is meaningful?)

The answer is yes (if you use the cPython implementation). The reason is Python’s global interpreter lock that ensures that a thread that’s currently working on it’s code will first finish its current basic Python operation as defined by the cPython implementation. Only if it terminates with this operation will the next thread be able to access the computational resource. This is ensured with a sophisticated locking scheme by the cPython implementation.

The only thing you need to know is that each basic operation in the cPython implementation is atomic. It’s executed wholly and at once before any other thread has the chance to run on the same virtual engine. Therefore, there are no race conditions. An example for such a race condition would be the following: the first thread reads a value from the list, the second threads overwrites the value, and the first thread overwrites the value again invalidating the second thread’s operation.

All cPython operations are thread-safe. But if you combine those operations into higher-level functions, those are not generally thread safe as they consist of many (possibly interleaving) operations.

Python List Clear Duplicates


How to remove all duplicates of a given value in the list?

The naive approach is to go over each element and check whether this element already exists in the list. If so, remove it. However, this takes a few lines of code.

A shorter and more concise way is to create a dictionary out of the elements in the list. Each list element becomes a new key to the dictionary. All elements that occur multiple times will be assigned to the same key. The dictionary contains only unique keys—there cannot be multiple equal keys.

As dictionary values, you simply take dummy values (per default).

Related blog articles:

Then, you simply convert the dictionary back to a list throwing away the dummy values. As the dictionary keys stay in the same order, you don’t lose the order information of the original list elements.

Here’s the code:

>>> lst = [1, 1, 1, 3, 2, 5, 5, 2]
>>> dic = dict.fromkeys(lst)
>>> dic
{1: None, 3: None, 2: None, 5: None}
>>> duplicate_free = list(dic)
>>> duplicate_free
[1, 3, 2, 5]

Where to Go From Here?


The list.clear() method removes all elements from the list.

You’ve learned the ins and outs of this important Python list method.

If you keep struggling with those basic Python commands and you feel stuck in your learning progress, I’ve got something for you: Python One-Liners (Amazon Link).

In the book, I’ll give you a thorough overview of critical computer science topics such as machine learning, regular expression, data science, NumPy, and Python basics—all in a single line of Python code!

Get the book from Amazon!

OFFICIAL BOOK DESCRIPTION: Python One-Liners will show readers how to perform useful tasks with one line of Python code. Following a brief Python refresher, the book covers essential advanced topics like slicing, list comprehension, broadcasting, lambda functions, algorithms, regular expressions, neural networks, logistic regression and more. Each of the 50 book sections introduces a problem to solve, walks the reader through the skills necessary to solve that problem, then provides a concise one-liner Python solution with a detailed explanation.



https://www.sickgaming.net/blog/2020/03/...ist-clear/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] Python’s NameError: name ‘xxx’ is not defined — How to Fix This Stupid Bug? xSicKxBot 0 9 10-16-2020, 10:30 PM
Last Post: xSicKxBot
  [Tut] Python IndentationError: unexpected indent (How to Fix This Stupid Bug) xSicKxBot 0 18 10-10-2020, 08:24 PM
Last Post: xSicKxBot
  [Tut] Yield Keyword in Python – A Simple Illustrated Guide xSicKxBot 0 18 10-09-2020, 06:13 PM
Last Post: xSicKxBot
  [Tut] Python Reverse List with Slicing — An Illustrated Guide xSicKxBot 0 29 10-02-2020, 04:24 AM
Last Post: xSicKxBot
  [Tut] How to Remove Duplicates From a Python List While Preserving Order? xSicKxBot 0 31 10-01-2020, 02:21 AM
Last Post: xSicKxBot
  [Tut] How To Update A Key In A Dictionary In Python If The Key Doesn’t Exist? xSicKxBot 0 34 09-29-2020, 09:02 PM
Last Post: xSicKxBot
  [Tut] How to Get the Last Element of a Python List? xSicKxBot 0 34 09-28-2020, 02:36 AM
Last Post: xSicKxBot
  [Tut] List Changes After Assignment — How to Clone or Copy It? xSicKxBot 0 34 09-27-2020, 12:14 AM
Last Post: xSicKxBot
  [Tut] How To Format A String That Contains Curly Braces In Python? xSicKxBot 0 31 09-25-2020, 07:51 PM
Last Post: xSicKxBot
  [Tut] Python One Line Dictionary xSicKxBot 0 40 09-21-2020, 05:58 PM
Last Post: xSicKxBot

Forum Jump:

Become a Patron!
[-]
Upcoming Events

[-]
Latest Threads
News - Torchlight III Arrives On Switch ...
Last Post: xSicKxBot
Today 08:19 AM
» Replies: 0
» Views: 1
News - Assassin's Creed Valhalla – Relea...
Last Post: xSicKxBot
Today 07:02 AM
» Replies: 0
» Views: 2
[Tut] Freelancer Invoice Template
Last Post: xSicKxBot
Today 05:08 AM
» Replies: 0
» Views: 1
(Indie Deal) Alien Cat Bundle, RIDE 4 re...
Last Post: xSicKxBot
Today 05:08 AM
» Replies: 0
» Views: 2
News - 2D Metroidvania DeathStick Brings...
Last Post: xSicKxBot
Today 01:16 AM
» Replies: 0
» Views: 3
News - Nintendo Download: 22nd October (...
Last Post: xSicKxBot
Today 01:16 AM
» Replies: 0
» Views: 2
News - Borderlands 3: New Moze And Zane ...
Last Post: xSicKxBot
Today 12:29 AM
» Replies: 0
» Views: 4
Exporting From Unity To Other Game Engin...
Last Post: xSicKxBot
Yesterday 11:23 PM
» Replies: 0
» Views: 4
Xbox one SDK Leaked: homebrew coming soo...
Last Post: DanielChapell
Yesterday 05:51 PM
» Replies: 1
» Views: 1764
News - Here's How The Walking Dead Is Fi...
Last Post: xSicKxBot
Yesterday 05:50 PM
» Replies: 0
» Views: 4

[-]
Twitter

[-]
Sponsored
Get the Deal of the Week at RefurBees.com

Copyright © SickGaming.net 2012-2020