Each of next() and list() iterates over generator with mutable object differently

前端 未结 3 887
孤城傲影
孤城傲影 2021-01-25 10:27
def generator(dct):
    for i in range(3):
        dct[\'a\'] = i
        yield dct

g = generator({\'a\': None})
next(g) # -> {\'a\': 0}
next(g) # -> {\'a\': 1}
n         


        
3条回答
  •  北恋
    北恋 (楼主)
    2021-01-25 11:18

    They iterate over the iterator identically, but you're checking in at different points. Because dicts are mutable, and you always yield the same dict, you should expect everything you yield to be identical. In your first example, you are looking at the dict as it is changing. Instead consider

    g = generator({'a': None})
    
    a = next(g)
    b = next(g)
    c = next(g)
    
    print(a, b, c)
    # {'a': 2} {'a': 2} {'a': 2}
    

提交回复
热议问题