0
Please help me understand the full effect of the elements in the code.
secret_list = [[5, 4] for i in range(4)] print(secret_list[2][1]) # The elements on line 2, can someone help me understand the purpose and the effect ‘[2][1]’ has on the code output.
5 Réponses
+ 1
secret_list is a list containing four lists and looks like this:
[[5, 4], [5, 4], [5, 4], [5, 4]]
The 2 in
secret_list[2][1]
refers to the list at index 2, i.e. the third list (Python is zero based)
the 1 refers to the element at index 1 of this list.
+ 2
secret_list is a list of lists.
"secret_list[2][1]" refers to the object at index 1 of the list at index 2 of secret_list.
0
Simon Sauter
Thanx i’m still a but confused what effect [2] on line 3 has. What is [2] making reference to?
0
Simon Sauter
Thank you very much!
0
I also had some issues with this question and the previous explanations provided here. I broke it down in the Python REPL to finally understand what Simon was stating:
>>> secret_list = [[5, 4] for i in range(4)]
>>> secret_list
[[5, 4], [5, 4], [5, 4], [5, 4]]
secret_list variable for the range produces [5,4] four times.
>>> print(secret_list[2][1])
secret_list at index 2 refers to the third [5, 4] (computers start counting at 0): [5, 4][5, 4][5, 4] <== index 2
[2][1] refers to the second element in index 2 (again, computers start counting at 0): [5, 4] <== index 2, element 1 is 4.
That's what finally made sense to me. Anyone else smarter than me at this can correct any errors I've listed. I hope this helps someone.