+ 2

What is the result of this code? nums = list(range(5)) print(nums[4])

What is the result of this code? nums = list(range(5)) print(nums[4]) please explain also.....

12th May 2017, 6:47 AM
Deepak Agrawal
Deepak Agrawal - avatar
12 Respostas
+ 16
When you run the code: >> nums = list(range(5)) >>print(nums[4]) >>4 So, this is the output: 4 Explaination: 1. In line 1, you called the range() function by giving it value: 5. Then converted it into a list. And finally assigned the list to a variable: nums. # range(0,x) means it takes all the values from 0 to x-1 (including 0 and x-1) # So, when you called range(0,5), it took all the values from 0 to 4 (including 0 and 4) # Therefore the variable: nums got the list assigned as: nums = [0,1,2,3,4] 2. In line 2, you printed (or displayed) the value in nums[4], which is undoubtedly: 4. # As here: nums[0] = 0, nums[1] = 1, nums[2] = 2, nums[3] = 3 and nums[4] = 4 3. Hence, in line 3, you got the output: 4. Hope you got it! Happy coding! 👍😉
12th May 2017, 7:08 AM
Ashutosh Tripathy
Ashutosh Tripathy - avatar
+ 7
I am not an expert in Python but I will try to explain. range(5) will create a range object with 0 inclusive 5 items. so it will be 0 to 4. list function will convert the range object to a list. so nums list will be nums = [0,1,2,3,4] hope you understand now and I am sure Python experts will write a explanation more clearly.
12th May 2017, 7:07 AM
Apel Mahmod
Apel Mahmod - avatar
+ 1
What is the result of this code? nums = [1, 2, 3, 4, 5] nums[3] = nums[1] print(nums[3]) The answer will be 2
15th Feb 2019, 3:33 PM
Mayur Patel
Mayur Patel - avatar
+ 1
answer is 4
23rd Jul 2019, 7:34 PM
Md Rakibul Islam
Md Rakibul Islam - avatar
0
4
24th Jan 2020, 6:16 AM
sasirekha.k
0
4
15th Sep 2020, 8:51 AM
Saran M
Saran M - avatar
0
ans : 4
10th Feb 2021, 11:49 AM
Md Momin Uddin Hridoy
Md Momin Uddin Hridoy - avatar
0
answer is 4
24th May 2021, 9:44 AM
Hayder Jawad Al-ATBEE
Hayder Jawad Al-ATBEE - avatar
0
4
6th Aug 2021, 11:16 AM
Thompson Omoriame
0
4 :)
15th Dec 2022, 6:03 PM
sajad heydari
sajad heydari - avatar
0
Ans is 4
14th Jan 2023, 5:17 PM
Engr.Ayesha Liaqat
Engr.Ayesha Liaqat - avatar
- 1
What is the result of this code? nums = [1, 2, 3, 4, 5] nums[3] = nums[1] print(nums[3])
10th Aug 2018, 3:37 PM
IG RAK
IG RAK - avatar