Explain following code? | Sololearn: Learn to code for FREE!


Explain following code?

x,*y={1:2,3:4,5:6} print(x)

3/1/2020 8:07:18 AM

Amey Godse

11 Answers

New Answer


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.


Tibor Santa great answer.. thank you!


x = 1 y = [3, 5] When you add a "*" before a variable, then you are giving it all the left values.


the output is 1. So only the keys count and therefore y = [3,5]


Aymane Boukrouh [INACTIVE] need you here Seb TheS Tibor Santa


Mirielle👽 Common for tuples but never seen in dict🤔


Did yo finish the course https://www.sololearn.com/learn/Python/2485/


Mirielle👽 good aspect ☝️ Oma Falk I think this is not the emoti you intended to use ;) 😂😂 no the 2nd one


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)


Oma Falk I'm sure you must have seen it in duct but you're not aware ... Are you familiar with this line def ( **kwargs ) # unpack dict