Explain following code? | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula gr√°tis
+ 5

Explain following code?

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

1st Mar 2020, 8:07 AM
Amey Godse
Amey Godse - avatar
8 Respostas
+ 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.
1st Mar 2020, 9:09 AM
Tibor Santa
Tibor Santa - avatar
+ 7
Tibor Santa great answer.. thank you!
1st Mar 2020, 9:40 AM
Oma Falk
Oma Falk - avatar
+ 6
x = 1 y = [3, 5] When you add a "*" before a variable, then you are giving it all the left values.
1st Mar 2020, 8:30 AM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 5
the output is 1. So only the keys count and therefore y = [3,5]
1st Mar 2020, 8:32 AM
Oma Falk
Oma Falk - avatar
1st Mar 2020, 8:24 AM
Oma Falk
Oma Falk - avatar
+ 3
MirielleūüĎĹ Common for tuples but never seen in dictūü§Ē
1st Mar 2020, 9:42 AM
Oma Falk
Oma Falk - avatar
+ 2
MirielleūüĎĹ good aspect ‚ėĚÔłŹ Oma Falk I think this is not the emoti you intended to use ;) ūüėāūüėā no the 2nd one
1st Mar 2020, 2:01 PM
Oma Falk
Oma Falk - avatar
+ 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)
2nd Mar 2020, 7:32 AM
E_E Mopho
E_E Mopho - avatar