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…
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.
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?))
As it turns out, my_list[:]
creates a copy of my_list
.
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.
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.