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.

Want to respond with a comment or question, or have some feedback?
Email and Twitter are good direct options, but you could also write a piece of your own and send me the link. :)