Nik Kantar

Thursday, October 5, 2017

✶ Modifying a List in Place in Python

A neat (if questionably legible) trick for modifying a list in place in Python, and a more Pythonic solution for the same problem.

One of the talks at the most recent meeting of SoCal Python was about generators and in the Q&A session after it somehow we landed on modifying a list in place. I'd like to share with you something neat I learned.

But first…

Why can't you modify the list in place the obvious way?

Let's find out!

>>> my_list = list(range(5))  # [0, 1, 2, 3, 4]
>>> for element in my_list:
...     my_list.remove(element)
...
>>> my_list
[1, 3]

Turns out that because of how list iteration works in Python, we skip every other element. That's not exactly great.

OK, so how do you do it?

Here's some syntactic sugar:

>>> my_list = list(range(5))  # [0, 1, 2, 3, 4]
>>> for element in my_list[:]:  # note what we're iterating through
...     my_list.remove(element)
...
>>> my_list
[]

(The [:]: notation almost looks like a little robot emoticon. (Remember emoticons? Before emoji?))

Wat

As it turns out, my_list[:] creates a copy of my_list.

Is that it?

There are other ways to copy a list that may be more legible, though. Here's one:

>>> my_list = list_copy = list(range(5))  # [0, 1, 2, 3, 4]
>>> for element in list_copy:  # again note what we're iterating through
...     my_list.remove(element)
...
>>> my_list
[]

This is probably the more maintainable method of the two, but I don't find it as…fun.


Tags: programming, python

Thanks for reading! You can keep up with my writing via the feed or newsletter, or you can get in touch via email or Mastodon.


Older:
Crush Cancer 2017
Newer:
Goals for 2017 in Review