LoginSignup
3
2

More than 3 years have passed since last update.

iteration 中に要素を追加できるか

Last updated at Posted at 2018-08-26

ちょっと驚いたネタ。iteration 中に要素を追加できるか。実は list は特殊で、できるらしい。

a.py
q = [1,2,3]
for a in q:
    print(a)
    if a==1:
        q.append(4)
b.py
import collections

q = collections.deque([1,2,3])
for a in q:
    print(a)
    if a==1:
        q.append(4)

実行結果は

$ python a.py
1
2
3
4

$ python b.py
1
Traceback (most recent call last):
  File "b.py", line 4, in <module>
    for a in q:
RuntimeError: deque mutated during iteration

SQLAlchemy で踏んだのだけれど、意図的なものらしい。実際には 闇が深い


bitbucket に何かあったらしく、以前の sqlalchemy は sqlalchemy_old に移動されて、新しく sqlalchemy repository が作られています。上記のリンクは古いほうを指すように更新しました。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2