Why does this assigned object share the same memory space as the original object?

前端 未结 2 1337
攒了一身酷
攒了一身酷 2021-01-27 09:10

In python I came across this strange phenomena while working with itertools groupby module.

In python, variable assignment means assigning the new variable its own memor

2条回答
  •  孤独总比滥情好
    2021-01-27 09:33

    In python, variable assignment means assigning the new variable its own memory instead of a pointer to the original memory

    Python has mutable (e.g. lists, iterators, just about everything) and immutable objects (e.g. integers and strings). Assignment does not copy the object in either case. With immutable objects, all operations on them result in a new instance, so you won't run into the problem of "modifying" an integer or a string like you do with mutable types.

    My question is why does this happen? Shouldn't assigning group to toup means toup would have a copy of groups memory at a different hex address location?

    Both variables will point to the same object. When you iterate over one and exhaust the iterator, iterating over the second variable will give you an empty sequence.

提交回复
热议问题