+ 1

Help me by explaining this code.

nums = [(X,X**2) for X in range (1,5)] print (nums [2] [1]) The output is 9 I don't really understand how the output is 9, so if someone could help me by offering a step-by-step explanation that would be great!

9th Jul 2017, 8:59 PM
G3cko
G3cko - avatar
2 Respostas
+ 10
nums is attributed a so-called "list comprehension", a special statement for creating lists or other collections. It tells Python to create a list of tuples (x, x**2) where x takes values of 1 to 4. So it goes: [(1, 1**2), (2, 2**2), (3, 3**2), (4, 4**2)] which of course equals to [(1, 1), (2, 4), (3, 9), (4, 16)] Then you call the list's element number [2] - (3, 9) - and access the tuple's element number [1] - equal to 9.
9th Jul 2017, 9:18 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
0
Didn't know what tuples were yet, so that caused some confusion, but I get it now. Thanks!
9th Jul 2017, 9:25 PM
G3cko
G3cko - avatar