0
nest list with len function need help
i have tried to figure why this code gives the output of down below. I dont get how nums = [1, 2, 3, [ 1, 2, 3, [ 2 ,5 , [3] ] ], 4, 5, 6, [ ] ] print (len (nums )) print(len(nums[3])) print (len (nums [3][3])) print (len (nums [3][3][2])) print (len (nums[7])) output 8 4 3 1 0
9 ответов
+ 2
So, to explain the question you asked:
nums = 1,2,3,[1,2,3,[2,5,[3]]],4,5,6,[]]
print(len(nums)) #8
This is 8 because nums has 8 elements - int, int, int, list, int, int, int, list.
print(len(nums[3])) #4
This is 4 because nums[3] is [1,2,3,[2,5,[3]]] and it has 4 elements - int, int, int, list.
print(len(nums[3][3])) # 3
This is 3 because nums[3] is [1,2,3,[2,5,[3]]] so nums[3][3] is [2,5,[3]] which has 3 elements - int, int, list.
print(len(nums[3][3][2])) #1
This is 1 because (from above) nums[3][3] is [2,5,[3]] so nums[3][3][2] is [3] which has 1 element.
print(len(nums[7])) #0
This is 0 because nums[7] is an empty list ([]) so it has 0 elements.
Does that make it any clearer?
+ 1
You can nest lists like this:
lst = [0,1,2,[0,1],4,5,[0,1,2,[0,1,2]]]
I've done it like this so that each number is the same as its index position in its list.
So here, lst[0] is 0, but lst[3] is the list [0,1], so lst[3][0] is 0. Also lst[6][3][1] is 1.
In your example nums[3] is [1,2,3,[2,5,[3]]], so nums[3][3] is [2,5,[3]], so nums[3][3][2] is the element at index 2 of nums[3][3] which is [3].
nums has a length 8 because it has 8 elements - i.e. [1,2,3,<list>,4,5,6,<empty list>] which makes 8.
+ 1
Ok, I'll start from the very start.
nums = [1,2,3]
print(len(nums)) #3
This is 3 because nums has 3 elements.
nums = [1,2,3,[4,5]]
print(len(nums)) #4
This is 4 because nums has 4 elements - 3 ints and 1 list.
print(len(nums[3])) # 2
This is 2 because the element at index 3 of nums is a list with 2 elements.
print(nums[3][0]) #4
This is 4 because nums[3] is the list [4,5] so nums[3][0] is [4,5][0] which is the element at index 0 of nums[3] ([4,5]) which is 4.
nums = [1,2,[3,4,5,[6,7]]]
print(len(nums)) #3
This is 3 because nums has 3 elements - 2 ints and 1 list. Note, it doesn't matter how many nested lists are inside, it is still only 1 list and thus 1 element.
+ 1
Ty so much I will study this
0
I still dont understand your answer i found this code from someone else and I tried to figure it out
0
Ok, let's break it down. Which part or parts are confusing you?
0
What I need help with is an explanation how do these codes work
When I look at nums I see a nest list with several list inside
0
How does (len(nums )) get you output get you 8
How does Len(nuns [3])) get you output 4
How does Len(nums[3][3])) get you output 3
How does Len(nums[3][3][2])) get you output1
How does Len(nums[7])) get you output 0
0
I just wanted the solutions to the one I put at the top I just cant figure how that code gives those outputs I put above