简体   繁体   中英

what is the fastest way to empty a list in Python

What is the fastest way to empty a list in Python? Is clear() the fastest? Also, what is the most memory efficient way of doing it? I heard Reinitializing the list won't clear it but let GarbageCleaner delete the actual contents based on the remaining references.

Which way would be fastest, and if possible most memory efficient?

ls.clear() , del ls[:] , and ls[:]=[] are all identical in their performance:

$ python3 -m timeit -n 1000 "ls=list(range(10000)); ls.clear()"
1000 loops, best of 5: 219 usec per loop

$ python3 -m timeit -n 1000 "ls=list(range(10000)); del ls[:]"
1000 loops, best of 5: 215 usec per loop

$ python3 -m timeit -n 1000 "ls=list(range(10000)); ls[:]=[]"
1000 loops, best of 5: 218 usec per loop

I agree with the others that if you need to even think about these kinds of micro-optimizations you're using the wrong language.

I would always just use ls.clear() since that's the most obvious, most readable, and cleanest way imo.

This is the fastest way to do it:

list *= 0 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM