[PYTHON] Change the list in a for statement

Purpose

Conclusion

There is a subtle problem with changing sequences in annotation loops (this can only happen with mutable sequences, eg lists). An internal counter is used to keep track of which element is used next, and this counter is incremented at each iteration. The loop ends when this counter reaches the length of the sequence. From this, removing the current (or previous) element from the sequence in the suite skips the next element (because the position of the next element is the index of the current element that has already been processed). It will be. Similarly, if you insert an element in the suite before the current element in the sequence, the current element will be treated again in the next week of the loop. These specifications lead to nasty bugs. This can be avoided by making a temporary copy using slices of the entire sequence.

official.py


for x in a[:]:
    if x < 0: a.remove(x)

Background

How to write a bug? What should i do?

This is a bug

The element of foo_list that is being turned by the for statement has been deleted in the sequence. This may prevent the list from being turned to the end.

bug.py


for i in foo_list:
  if thres >= i:
      foo_list.remove(i)

I want to write this when I try to avoid a bug

First, turn all the for statements. Make a note of the element you want to erase. Turn the memod content with for to delete it.

Troublesome

no_good.py


memo = []
for i in range(len(foo_list)):
    if thres >= foo_list[i]:
      memo.append(foo_list[i])

for item in memo:
    foo_list.remove(item)

You can write neatly by referring to the formula

Create a new list object by slicing the entire range of the list specified by the for statement. It's the same as ʻa = foo_list [:]` when you want to copy

beautiful.py


for i in foo_list[:]:
  if thres >= i:
      foo_list.remove(i)

By the way, if you just want to filter as above, the inclusion notation is better as pointed out by @shiracamus below. Then I will add the story of using him again.

@shiracamus Isn't it quicker to create a new list with comprehension than to remove it from the list?

foo_list = [i for i in foo_list if thres >= i]

Recommended Posts

Change the list in a for statement
[Introduction to Python] How to use the in operator in a for statement?
Make a copy of the list in Python
Get only the subclass elements in a list
Python list, for statement, dictionary
Register a task in cron for the first time
Methods available in the list
Convenient to use matplotlib subplots in a for statement
Turn multiple lists with a for statement at the same time in Python
[Python / PyQ] 4. list, for statement
When you want to plt.save in a for statement
Change the standard output destination to a file in Python
A note for embedding the scripting language in a bash script
Note 2 for embedding the scripting language in a bash script
Get the number of specific elements in a python list
How to define multiple variables in a python for statement
How to get the last (last) value in a list in Python
Get the number of occurrences for each element in the list
Create a new list by combining duplicate elements in the list
[python] Manage functions in a list
When creating a matrix in a list
Parse the Researchmap API in Python and automatically create a Word file for the achievement list
Output the key list included in S3 Bucket to a file
Loop the For statement in reverse in an HTML file on Django
Change the bash prompt to a simple color for easy viewing
Put together consecutive values in the list
Display a list of alphabets in Python 3
Find the dates for a jarring tournament
OR the List in Python (zip function)
Cut out A4 print in the image
Run the Python interpreter in a script
MongoDB for the first time in Python
Get a token for conoha in python
Get the EDINET code list in Python
Arrange the numbers in a spiral shape
[Introduction to Udemy Python3 + Application] 47. Process the dictionary with a for statement
[Linux] Command to get a list of commands executed in the past
I want to sort a list in the order of other lists
Receive a list of the results of parallel processing in Python with starmap
A useful note when using Python for the first time in a while
[Python] How to create a dictionary type list, add / change / delete elements, and extract with a for statement
[IOS] Change the display time for each frame of GIF animation in Pythonista3.
How to pass the execution result of a shell command in a list in Python
CERTIFICATE_VERIFY_FAILED in Python 3.6, the official installer for macOS
[Python] Get the files in a folder with Python
Japanese text preprocessing without for statement in pandas
Use something other than a <br> string for the <br> dict key in Python
Receives and processes n objects in a list
[Python] Sort the list of pathlib.Path in natural sort
Created a Python wrapper for the Qiita API
How to clear tuples in a list (Python)
Change the device (drive) label in vfat format.
Use the latest pip in a virtualenv environment
Change the font size of the legend in df.plot
Change the default reference repository for pip install
Get the caller of a function in Python
A note on customizing the dict list class
Make a histogram for the time being (matplotlib)
Extract the product name and price from the product list in the Yodobashi.com purchase statement email.
Find the number of days in a month
A program that searches for the same image