SoFunction
Updated on 2024-11-19

Does changing data during traversal of a python iterable type report an error?

test

1.1 Lists

a = [1, 2, 3, 4]
for i in a:
    print(i)
    (i)
a
exports:
1
3

1.2 dict

a = {'a': 1, 'b': 2}
for i in a:
    print(i)
    (i)
a

Output:

1.3 Collections

a = {1, 2, 3, 4}
for i in a:
    print(i)
    (i)
a

1.4 Tuples

a = (1, 2, 3, 4)
for i in a:
    print(i)
    (i)
a

reach a verdict

  • The list can be changed without reporting an error
  • Dictionary, collection type change in the middle, will report an error
  • Tuple data types are immutable

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.