Table of Contents
Correct Answer
Home Backend Development Python Tutorial Strange results when removing items from list while iterating over list in Python

Strange results when removing items from list while iterating over list in Python

Feb 09, 2024 am 10:10 AM
implicit conversion

在 Python 中迭代列表时从列表中删除项目时出现奇怪的结果

Question content

I have this code:

numbers = list(range(1, 50))

for i in numbers:
    if i < 20:
        numbers.remove(i)

print(numbers)
Copy after login

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...]
 ^
Copy after login

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...]
       ^
Copy after login

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]
Copy after login

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)
Copy after login

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]
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use short in java How to use short in java May 07, 2024 am 03:33 AM

short is a primitive data type in Java that represents a 16-bit signed integer in the range -32,768 to 32,767. It is often used to represent small integers, such as counters or IDs, and supports basic arithmetic operations and type conversions. But since short is a signed type, you need to be careful when using division to avoid overflow or underflow.

Usage of ifnull in sql Usage of ifnull in sql Apr 28, 2024 am 09:57 AM

The IFNULL function checks whether an expression is NULL and returns the specified default value if so, otherwise it returns the value of the expression. It prevents null values ​​from causing errors, allows manipulation of null values, and improves the readability of queries. Usage includes: replacing null values ​​with default values, excluding null values ​​from calculations, and nested usage to handle multiple null value situations.

How to calculate division in c language How to calculate division in c language Apr 13, 2024 pm 09:12 PM

In C language, the behavior of the division operator / depends on the data type of the operands: Integer division: When the operand is an integer, integer division is performed and the result is rounded down. Floating point division: When the operand is a floating point number, floating point division is performed and the result is a floating point number. Type conversion: When one operand is an integer and the other is not, the integer is implicitly converted to a floating point number, and then floating point division is performed. Divisor by 0: A mathematical error occurs when the divisor is 0. Modulo operation: Use the % operator for modulo operation instead of modulo division.

What does char in java mean? What does char in java mean? May 01, 2024 pm 06:15 PM

The char type in Java is used to store a single Unicode character, accounting for 2 bytes, ranging from U+0000 to U+FFFF. It is mainly used to store text characters. It can be initialized through single quotes or Unicode escape sequences, and can participate in comparison, Equality, inequality and join operations can be implicitly converted to int type or explicitly converted to Character objects.

What are the matching rules for C++ function overloading? What are the matching rules for C++ function overloading? Apr 27, 2024 am 08:27 AM

The C++ function overload matching rules are as follows: match the number and type of parameters in the call. The order of parameters must be consistent. The constness and reference modifiers must match. Default parameters can be used.

Usage of (+ in oracle Usage of (+ in oracle May 08, 2024 pm 08:12 PM

The plus (+) operator in Oracle can be used to: connect strings, numbers, dates, and time intervals; handle NULL values ​​and convert NULL to non-NULL values; convert data types to string types.

What are the PHP function parameter types? What are the PHP function parameter types? Apr 10, 2024 pm 04:21 PM

PHP function parameter types include scalar types (integers, floating point numbers, strings, Boolean values, null values), composite types (arrays, objects) and special types (callback functions, variable parameters). Functions can automatically convert parameters of different types, but they can also force specific types through type declarations to prevent accidental conversions and ensure parameter correctness.

Let's explore common application scenarios of implicit type conversion! Let's explore common application scenarios of implicit type conversion! Jan 11, 2024 pm 04:45 PM

Let’s explore common application scenarios of implicit type conversion! Introduction: In programming languages, implicit type conversion is an automatically performed data type conversion process. In some programming languages, this conversion is performed implicitly, without the need to explicitly tell the compiler or interpreter to perform the conversion. Implicit type conversion has a wide range of application scenarios in programming. This article will discuss some of the common application scenarios. Implicit type conversion in numerical calculations In numerical calculations, operations between different types of data are often required. When different types of data

See all articles