can anyone explain this code: - nums=list(range(5)) print(nums[4]) output :-4 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

can anyone explain this code: - nums=list(range(5)) print(nums[4]) output :-4

31st Oct 2016, 4:15 AM
Johnson Chaudhary
Johnson Chaudhary - avatar
5 Answers
+ 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
31st Oct 2016, 9:50 PM
Ugra Narasimha
Ugra Narasimha - avatar
+ 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
31st Oct 2016, 4:54 AM
Waqas Asghar Bhalli
Waqas Asghar Bhalli - avatar
+ 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)
31st Oct 2016, 4:17 AM
Kapil Chaitanya Kasarapu
Kapil Chaitanya Kasarapu - avatar
+ 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
8th Dec 2018, 10:55 PM
Matt Dickey
Matt Dickey - avatar
0
thank you very much for sorting out this problem.
1st Nov 2016, 1:50 AM
Johnson Chaudhary
Johnson Chaudhary - avatar