+ 2

Why is "myval = [(2,3)][0][-2]" 2?

Can somebody explain why this line of code: myval = [(2,3)][0][-2] results in myval beeing a integer with the value 2?

26th Jul 2017, 1:52 PM
Martin Ed
Martin Ed - avatar
2 Answers
+ 2
myvar=[(2,3,4),(5,6,7)][1][2] #myvar will be 7 Firstly you create a list (with two tuples inside in this case), then you indicate the position of the value you want to take; [1] indicates the second tuple (they start from 0, remember) [2] indicates the third number, in this case 7, so myval will be 7 myval = [(2,3)][0][-2] #[0] represents the first list, in this case is the only one available in your example there is also [-2], it only means that it will start counting from the end, so [-2] is 2 [-1] is 3 [0] is 2 [1] is 3 This kind of problem is often solvable changing the numbers that you have, seeing if it gives you any error and trying to understand what they means.
26th Jul 2017, 2:09 PM
Matte
Matte - avatar
+ 3
It's simple [(2, 3)] is an array having one tuple which is (2,3). So indexing it with 0 will give you the first and only member of the array i.e. [(2, 3)] [0] == (2, 3). Again if you are indexing [(2,3)] [0] with any index, it will give you the corresponding integer inside the tuple. Simply, [(2, 3)] [0] [-2] is the same as (2, 3) [-2]. If you use positive values: (2, 3) [0] == 2 (2, 3) [1] == 3 but if you use negative value, the counting will start from the right. i.e. (2, 3) [-1] == 3 (2, 3) [-2] == 2 Hope it helped :)
26th Jul 2017, 2:21 PM
Hanif Ali
Hanif Ali - avatar