[Python Beginner] Question why the results depend on the difference in the empty dictionary declaration position (in or out) in the for statement

Asked 2 years ago, Updated 2 years ago, 82 views

Hello, I'm a beginner at Python.

I want to create a dictionary that increases sequentially with a for statement and add it to one list It depends on the difference in the position of the empty dictionary declaration (whether outside the for door or inside the for door), so it doesn't work well to try to understand why. Can someone explain it easily?

Below is an example image that I created, the In [8] script works fine, and the In [7] script seems to work fine, but in [7], only the last value is entered repeatedly, so I don't understand well.

In [7], b={} made outside the for door worked, adding b["order"] = i immediately, and then adding a.append when the order turns to i+1 again, I thought it would continue to update the b["order"]= i+a>

I'd like to ask you about your opinions.

python for dictionary

2022-09-20 19:15

1 Answers

In 7, after the append of b, changing the contents of b continues to affect what has already been appended before. In other words, we appended b to a, but at that point, the relationship between b outside and b appended continues. Because it's the same b.

On the other hand, in 8 we recreate b={} in the for loop every time. Every time a new dictionary is created in the variable b, it is different from the previous one that was appended.

>>> b = {}
>>> a = []
>>> for i in range(7):
    b['''] = i
    a.append(dict(b))


>>> a
[{''': 0}, {''': 1}, {''': 2}, {''': 3}, {''': 4}, {''': 5}, {''': 6}]

In this example, although b is declared outside, I think the result came out the way the questioner wanted it to. This time, I changed b because the attached dictionaries didn't affect it because when I did the append, I made a copy of b and made another instance and appended it.

It's very confusing when you first encounter Python, and in summary, when you call a function with a variable set (I don't know if the term is correct) such as list and dict, it works in a way that goes beyond the reference (like a pointer to c) instead of copying the content.

It's confusing, but if you think about why, I think this implementation came out because it's expensive to copy all the collective variables.

So, when you hand over the list, dict, etc. with a factor, you can copy it and hand it over when you need it... That's right.


2022-09-20 19:15

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.