0

I have a code:

keys = {'a','e','i','o','u'}
value = [1]
vowels = { key : list(value) for key in keys }
print(vowels)
value.append(2)
print(vowels)

The result of this code:

{'a':[1],'e':[1],'i':[1],'o':[1],'u':[1]}
{'a':[1],'e':[1],'i':[1],'o':[1],'u':[1]}

The following code:

keys = {'a','e','i','o','u'}
value = [1]
vowels = { key : value for key in keys }
print(vowels)
value.append(2)
print(vowels)

gives me another result:

{'a':[1],'e':[1],'i':[1],'o':[1],'u':[1]}
{'a':[1,2],'e':[1,2],'i':[1,2],'o':[1,2],'u':[1,2]}

Why it happens if value and list(value) are both give the same list object?

azro
  • 53,056
  • 7
  • 34
  • 70

1 Answers1

0

The code list(value) create a new list with the content of value, so if you modify value after, that has no effect.

value = [1] ---> a list instance
{
 'u': [1], ----> a list instance copied from value
 'a': [1], ----> a list instance copied from value
 'e': [1], ----> a list instance copied from value
 'i': [1], ----> a list instance copied from value
 'o': [1]  ----> a list instance copied from value
 }

But in vowels = {key: value for key in keys} you set the unique instance of the list value as the value of each key, all refers to the unique list [1] so of you modify it, you can see it in the dict as that list is being used

value = [1,2] ---> a list instance
{                  ^
 'u': [1, 2], -----|    refers to value object
 'a': [1, 2], -----|    refers to value object
 'e': [1, 2], -----|    refers to value object
 'i': [1, 2], -----|    refers to value object
 'o': [1, 2]  -----|    refers to value object
}
azro
  • 53,056
  • 7
  • 34
  • 70