![]() |
|
[Tut] list.clear() vs New List — Why Clearing a List Rather Than Creating a New One? - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] list.clear() vs New List — Why Clearing a List Rather Than Creating a New One? (/thread-98535.html) |
[Tut] list.clear() vs New List — Why Clearing a List Rather Than Creating a New One? - xSicKxBot - 11-30-2020 list.clear() vs New List — Why Clearing a List Rather Than Creating a New One? Problem: You’ve just learned about the Code: list.clear()Example: Say, you have the following list. Code: lst = ['Alice', 'Bob', 'Carl']If you clear the list, it becomes empty: Code: lst.clear()
print(lst)
# []However, you could have accomplished the same thing by just assigning a new empty list to the variable Code: lstCode: lst = ['Alice', 'Bob', 'Carl']
lst = []
print(lst)
# []The output is the same. Why does the Code: list.clear()If you go through the following interactive memory visualizer, you’ll see that both variants lead to different results if you have multiple variables pointing to the list object: https://pythontutor.com/iframe-embed.html#code=lst_1%20%3D%20%5B'Alice',%20'Bob',%20'Carl'%5D%0Alst_2%20%3D%20lst_1%0Alst_1.clear%28%29%0A%0A%0A%0Alst_1%20%3D%20%5B'Alice',%20'Bob',%20'Carl'%5D%0Alst_2%20%3D%20lst_1%0Alst_1%20%3D%20%5B%5D%0A&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=1&heapPrimitives=nevernest&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false In the second example, the variable Code: lst_2So, there are at least two reasons why the Code: list.clear()
Do you want to develop the skills of a well-rounded Python professional—while getting paid in the process? Become a Python freelancer and order your book Leaving the Rat Race with Python on Amazon (Kindle/Print)! ![]() The post list.clear() vs New List — Why Clearing a List Rather Than Creating a New One? first appeared on Finxter. |