3

I know there are several ways to resize lists, including creative list comprehensions and slicing:

For example, with slices:

values = values[:-50]

However, it seems these methods that reassign back to the initial identifier would require a copy of the list being created in memory. Am I mistaken?

If you have a huge list that you cannot afford to create a copy of (say it is a massive list over half the size of your available memory), is there anyway to resize a list in place?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Ray
  • 40,256
  • 21
  • 101
  • 138

1 Answers1

8

Use a del statement on the slice:

del values[-50:]

This removes those last 50 elements without creating a new list.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I hate drive-by downvotes too. BTW, I don't see my question as a duplicate as the referred to question does no call out any notion of wanting to resize in place for memory limitations, even if the answer to my question is you need to trim the list. – Ray Aug 18 '16 at 14:24
  • @Ray: the second answer there answers your question directly though. – Martijn Pieters Aug 18 '16 at 14:26
  • Agreed. However, knowing the answers are the same does not mean the context of the questions are necessarily the same. – Ray Aug 18 '16 at 14:35