Clearing a list

I find it annoying that I can't clear a list. In this example:

a = []
a.append(1)
a.append(2)

a = []

The second time I initialize a to a blank list, it creates a new instance of a list, which is in a different place in memory, so I can't use it to reference the first, not to mention it's inefficient.

The only way I can see of retaining the same pointer is doing something like the following:

for i in range(len(a)):
    a.pop()

This seems pretty long-winded though, is there a better way of solving this?


Asked by: Rafael934 | Posted: 28-01-2022






Answer 1

You are looking for:

del L[:]

Answered by: Cadie679 | Posted: 01-03-2022



Answer 2

I'm not sure why you're worried about the fact that you're referencing a new, empty list in memory instead of the same "pointer".

Your other list is going to be collected sooner or later and one of the big perks about working in a high level, garbage-collected language is that you don't normally need to worry about stuff like this.

Answered by: Hailey602 | Posted: 01-03-2022



Answer 3

this can help you::)

L[:] = []

Answered by: Justin611 | Posted: 01-03-2022



Similar questions

python - How to keep pyglet from clearing the screen?

I want to draw a scene and sequentially add lines to it. But pyglet keeps updating without control :( , so all I get is blinks from pyglet.gl import * window=pyglet.window.Window() def drawline(): ... @window.event def on_draw(): drawline() pyglet.app.run() should I change the decorator(if there exist options) or what? Thanks!


python IRC buffer not clearing

I have a simply buffer system for my IRC bot so it never misses a line due to network lag and such. I am using the following code to start the loop that processes information received from the server: while 1: #Start the main loop self.readbuffer += s.recv(1024).decode() temp=self.readbuffer.split("\n") self.readbuffer=temp.pop() The problem is that it seems that the buffer nev...


python - clearing an entry widget box

I want to use an entry widget to get a number between 1 and 9. If any other key is pressed I want to remove it from the display. def onKeyPress(event): if event.char in ['1', '2', '3', '4', '5', '6', '7', '8', '9'] ...do something return # HERE I TRY AND REMOVE AN INVALID CHARACTER FROM THE SCREEN # at this point the character is: # 1) visible o...


Clearing the python IDLE screen in win7

This question already has answers here:


python - Anyway of clearing text in IDLE

Is there anyway of clearing text in IDLE, its really anoying when i run the script a couple of times and then there's a cluster of words which is really hard to read. and yes I have looked on google, stack_overflow and a couple of more websites but i cant find anything useful. I tried to do: import os def cls(): os.system("cls") >>>cls()


Python - Clearing the user input?

I'm pretty new to python, I'm using version 3.3.3. Let's say we have this script: name = "user" say = input("Say: ") print (name, "said:",say) If I run it, the output will be: Say: mytext user said: mytext I wanna know, is there a way to clear/delete the 'Say: mytext'? Just to make it a little bit clearer: I want: user said: hi ...


python clearing text box with button event

I am trying to clear the text box i typed already with a Button 'Clear'.But its not clearing the text once the button is clicked! Please fix my problem!Answer will be appreciated! import tkinter as tki class App(object): def __init__(self,root): self.root = root txt_frm = tki.Frame(self.root, width=600, height=400) txt_frm.pack(fill="both", expand=True) # ensure...


Clearing a group in Python

If I have a group of sprites such as: spriteList = pygame.sprite.Group() Is there anyway to delete all of the contents of the group?


python - clearing the screen with a key press in pygame

This question already has answers here:


Clearing the text from the python shell

This question already has answers here:


python - How to keep pyglet from clearing the screen?

I want to draw a scene and sequentially add lines to it. But pyglet keeps updating without control :( , so all I get is blinks from pyglet.gl import * window=pyglet.window.Window() def drawline(): ... @window.event def on_draw(): drawline() pyglet.app.run() should I change the decorator(if there exist options) or what? Thanks!


python - Django: Change models without clearing all data?

I have some models I'm working with in a new Django installation. Is it possible to change the fields without losing app data? I tried changing the field and running python manage.py syncdb. There was no output from this command. Renavigating to admin pages for editing the changed models caused TemplateSyntaxErrors as Django sought to display fields that didn't exist in the db. I am usi...


.net - Clearing a log file which is in use

On my job, I am working with a big .NET application which writes to a log file. Let's call the application CompanyApplication. I have written a simple Python script which clears the log: file_object = open('C:\\log.txt', 'w') file_object.write("") file_object.close() When CompanyApplication.exe is not running this works fine. However, when CompanyApplication...


python IRC buffer not clearing

I have a simply buffer system for my IRC bot so it never misses a line due to network lag and such. I am using the following code to start the loop that processes information received from the server: while 1: #Start the main loop self.readbuffer += s.recv(1024).decode() temp=self.readbuffer.split("\n") self.readbuffer=temp.pop() The problem is that it seems that the buffer nev...


Curses window in Python without clearing the terminal

Is there a way to initialize curses in Python without clearing the existing text in the terminal? What I have in mind is, that when I will execute my application, it will either "push" the existing text up and executes at the bottom of the screen, or will draw itself over the existing text. I think curses' newterm function can do that, but it isn't implemented in Python. Are there any other ways?


python - Clearing the screen in IPython

Is there a command in IPython to clear the screen? EDIT: As @Saher mentions below, I can clean the screen using import os; os.system('CLS'), but is there a way to do this without having to import all of os?


Clearing a cookie when using Twisted and Python

I am using twisted to fetch a page. For every callback to get a page....is the cookie reset? If not, how do I reset a cookie for every callback? Below is an example...I need a separate cookie for each reqest. client.getPage(iUrl,headers,method='GET',cookies= {}).addCallback(self.processPage,iUrl).addErrback(self.printError,iUrl) client.getPage(iUrl,headers,method='GET',cookies= {}).addCallback(self.pr...


python - Clearing specific cache in Django

I am using view caching for a django project. It says the cache uses the URL as the key, so I'm wondering how to clear the cache of one of the keys if a user updates/deletes the object. An example: A user posts a blog post to domain.com/post/1234/ .. If the user edits that, i'd like to delete the cached version of that URL by adding some kind of delete cache command at the end of the view that ...


python - clearing elements of numpy array

Is there a simple way to clear all elements of a numpy array? I tried: del arrayname This removes the array completely. I am using this array inside a for loop that iterates thousands of times, so I prefer to keep the array but populate it with new elements every time. I tried numpy.delete, but for my requirement I don't see the use of subarray specification. *Edited*: The ...


python - logging and clearing file

I am working on simple keylogger - import logging, sys, smtplib, pyHook, pythoncom, socket path = r"C:\Users\Karel\Desktop\log.txt" logging.basicConfig(filename=path, level=logging.DEBUG, format="%(message)s") server = smtplib.SMTP("smtp.gmail.com:587") server.starttls() server.login("xxx","xxx") def OnKeyboardEvent(event): print "Key: ", chr(event.Ascii) logging.log(10,chr(event.Ascii)) chec...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top