0

List Function

Hello guys! can you explain me this function? i'm so confused with this output where item's list starts with 0 yes but when i put "len" method, output will be confusing coz it mixed with the start of '0' and starts with '1'. nums = [1, 2, 3, [1, 2, 3, [2,5,[3]]], 4, 5, 6, []] print(len(nums[3][3])) print(len(nums[3][3][2])) #output: 3 1

15th Jan 2021, 12:12 PM
Yamo
Yamo - avatar
3 odpowiedzi
+ 4
First let me clarify what len is. len means length. print(len([1, 2, 3, 4])) >> 4 And for your case, that is a nested list. - - - - - - - - - - - - ( 1 ) print(len(nums[3][3])) First we have to get first the element list of nums[3][3] nums[3] = [1,2,3,[2,5,[3]]] Now let's get the fourth element of nums[3] nums[3][3] = [2, 5, [3]] And the length of this list is 3: First element: 2 Second element: 5 Third element: [3] - - - - - - - - - - - - ( 2 ) For the second one, we just need to get the third element of our previous list which is nums[3][3]. nums[3][3] = [2, 5, [3] ] nums[3][3][2] = [3] The third element or nums[3][3][2] is [3]. Now the length of [3] is 1. - - - - - - - - - - - - - - - If my explanation is still unclear, please feel free to ask. Thanks!
15th Jan 2021, 12:30 PM
noteve
noteve - avatar
+ 2
Nice! thank you so much for the very clear explanation! i got it now it search for the final item in the list then measure what its length.thanks!
15th Jan 2021, 12:54 PM
Yamo
Yamo - avatar
+ 1
I think you still need a little correction. It doesn't search anything and the final item is not important. The numbers in 'nums[3][3]' are indices! They start counting at 0. So we access nums, get the element with index 3, which is [1, 2, 3, [2,5,[3]]], and of that list again get the element with index 3, which is the list [2,5,[3]]. The length of that list is 3. In the next example we have a third index. So from the list [2,5,[3]] we get the element with index 2, which is [3], a list with 1 element. Add more output to get a better understanding: print(nums[3]) print(nums[3][3]) print(nums[3][3][2])
15th Jan 2021, 1:25 PM
Benjamin Jürgens
Benjamin Jürgens - avatar