+ 5
Explain following code?
x,*y={1:2,3:4,5:6} print(x)
8 Answers
+ 12
Normally if you iterate through a dictionary, you get the keys only:
for key in {1:2, 3:4, 5:6}:
print(key)
The same mechanism is used in the example above when unpacking the sequence of these keys to variables.
x, *y =
means the first element (in this case: dictionary key) is assigned to variable x, the rest of the elements to variable y.
This kind of unpacking did not really make a lot of sense in the past, because dictionary keys used to be in random order, but with recent Python versions at least the keys retain the same order they were added to the dict. So at least it is more predictable what is the FIRST key.
+ 7
Tibor Santa
great answer.. thank you!
+ 6
x = 1
y = [3, 5]
When you add a "*" before a variable, then you are giving it all the left values.
+ 5
the output is 1.
So only the keys count and therefore y = [3,5]
+ 3
+ 3
Mirielleđ˝
Common for tuples but never seen in dictđ¤
+ 2
Mirielleđ˝
good aspect âď¸
Oma Falk I think this is not the emoti you intended to use ;)
đđ no the 2nd one
+ 2
x, *y = {1:2, 3:4, 5:6}
this means assign the first value to variable x and the remaining values to y (*y ==> all others)