+ 1
can anyone explain this code: - nums=list(range(5)) print(nums[4]) output :-4
5 Antworten
+ 6
Range Function will give us range from to
In your example
range(5) - 0,1,2,3,4
list(range(5)) - [0,1,2,3,4]
As we know that List of index starts from 0 not 1 like An array
So according to this it will store like this
list[0] = 0 index
list[1] = 1 index
list[2] = 2 index
list[3] = 3 index
list[4] = 4 index
so nums[4] = 4
Ans: 4
+ 4
First of all range (5) function will generate numbers from 0 to 4
Then these number will be assign to the list named as nums.
After assigning nums list would be like this
nums = [0,1,2,3,4]
As we know list start with 0 Index so
print (nums [4])
Above print statement will display element of the list at index 4 which four. so 4 will be printed
+ 2
list(range(5)) creates a list of 0,1,2,3,4
4th element of this list is 4 (Remember the elements index starts from 0)
+ 1
the 4th element is actually 3. That is why its so confusing
element #1: 0
element #2: 1
element #3: 2
element #4: 3
0
thank you very much for sorting out this problem.