


Strange results when removing items from list while iterating over list in Python
I have this code:
numbers = list(range(1, 50)) for i in numbers: if i < 20: numbers.remove(i) print(numbers)
However, the result I get is:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
Of course, I hope that no number below 20 will appear in the result. Looks like I did something wrong when deleting.
Correct Answer
You are modifying the list while iterating over it. This means that the first time through the loop, i == 1
, so 1
is removed from the list. Then the for
loop goes to the second item in the list, which is not 2
, but 3
! It is then removed from the list and the for
loop continues with the third item in the list, which is now 5. So on and so forth. Maybe it's easier to visualize this, using ^ to point to the value of i
:
[1, 2, 3, 4, 5, 6...] ^
This is the initial state of the list; then 1
is deleted and the loop goes to the second item in the list:
[2, 3, 4, 5, 6...] ^ [2, 4, 5, 6...] ^
etc.
There is no good way to change the length of a list while iterating it. The best thing you can do is this:
numbers = [n for n in numbers if n >= 20]
Or this, for in-place changes (the thing in the brackets is a generator expression that is implicitly converted to a tuple before the slice is assigned):
numbers[:] = (n for n in numbers if n >= 20)
If you want to perform an operation on n
before deleting it, one trick you can try is:
for i, n in enumerate(numbers): if n < 20: print("do something") numbers[i] = None numbers = [n for n in numbers if n is not None]
The above is the detailed content of Strange results when removing items from list while iterating over list in Python. For more information, please follow other related articles on the PHP Chinese website!

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

NumPyallowsforvariousoperationsonarrays:1)Basicarithmeticlikeaddition,subtraction,multiplication,anddivision;2)Advancedoperationssuchasmatrixmultiplication;3)Element-wiseoperationswithoutexplicitloops;4)Arrayindexingandslicingfordatamanipulation;5)Ag

ArraysinPython,particularlythroughNumPyandPandas,areessentialfordataanalysis,offeringspeedandefficiency.1)NumPyarraysenableefficienthandlingoflargedatasetsandcomplexoperationslikemovingaverages.2)PandasextendsNumPy'scapabilitieswithDataFramesforstruc

ListsandNumPyarraysinPythonhavedifferentmemoryfootprints:listsaremoreflexiblebutlessmemory-efficient,whileNumPyarraysareoptimizedfornumericaldata.1)Listsstorereferencestoobjects,withoverheadaround64byteson64-bitsystems.2)NumPyarraysstoredatacontiguou

ToensurePythonscriptsbehavecorrectlyacrossdevelopment,staging,andproduction,usethesestrategies:1)Environmentvariablesforsimplesettings,2)Configurationfilesforcomplexsetups,and3)Dynamicloadingforadaptability.Eachmethodoffersuniquebenefitsandrequiresca

The basic syntax for Python list slicing is list[start:stop:step]. 1.start is the first element index included, 2.stop is the first element index excluded, and 3.step determines the step size between elements. Slices are not only used to extract data, but also to modify and invert lists.

Listsoutperformarraysin:1)dynamicsizingandfrequentinsertions/deletions,2)storingheterogeneousdata,and3)memoryefficiencyforsparsedata,butmayhaveslightperformancecostsincertainoperations.

ToconvertaPythonarraytoalist,usethelist()constructororageneratorexpression.1)Importthearraymoduleandcreateanarray.2)Uselist(arr)or[xforxinarr]toconvertittoalist,consideringperformanceandmemoryefficiencyforlargedatasets.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver CS6
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version
Useful JavaScript development tools
