+ 2

Little confusion with given list to identify the syntax issue

Which line of code will cause an error? num = [5, 4, 3, [2], 1] print(num[0]) print(num[3][0]) print(num[5]) Ans: line4 but not sure why line 4 is causing error?

17th Sep 2020, 5:34 PM
Abhi
Abhi - avatar
7 odpowiedzi
+ 7
Because the length of the list is 5 and num[5] does not exist.
17th Sep 2020, 5:39 PM
HBhZ_C
HBhZ_C - avatar
+ 6
Abhi here is a minor edit to your code and a little help explain position in the array https://code.sololearn.com/cn243ms9vQtN/?ref=app
17th Sep 2020, 5:42 PM
BroFar
BroFar - avatar
+ 3
The number in the list with 0 position is 5. And the number(list) in position 3 is [2] and the number in 0 position in this list ( [2] ) is 2. And the print(num[5]) is out of range ... There are only 5 elements in the list(till position 4). Remember that the counting of position starts from 0.
17th Sep 2020, 5:40 PM
Bartika🎶
Bartika🎶 - avatar
+ 2
index starts from 0 here index range is 0 to 4 print(num[5]) this line try to access index 5 , it's out of range That's why it's giving error
17th Sep 2020, 5:52 PM
Bhargava Ram
Bhargava Ram - avatar
+ 2
[2] means index of 2 num = [5,4,3,[2],1] 0 ,1,2,3 ,4 Value in index 2 is 3 So it's printing value 3
17th Sep 2020, 5:57 PM
Bhargava Ram
Bhargava Ram - avatar
+ 1
Abhi [2] is like a list within a list... It is a list in the list 'num' with 1 element.
17th Sep 2020, 5:55 PM
Bartika🎶
Bartika🎶 - avatar
0
Thanks all of you but may I know the meaning of [2] in the list ? as the list given as num = [5, 4, 3, [2], 1] so not sure how to understand [2] in this list while writing a code?
17th Sep 2020, 5:50 PM
Abhi
Abhi - avatar