When trying to compile below piece of code then getting below error:-
IndexError Traceback (most recent call last)
in
1 my_list = [[0,1,2,3] for i in range(2)]
----> 2 print(my_list[2][0])
IndexError: list index out of range
for below code:-
my_list = [[0,1,2,3] for i in range(2)]
print(my_list[2][0])
what should be done here to resolve this compilation error?
my_list[-1] will return -2 and my_list[-2] will return 1, which is what the print() function is displaying: -1 being the last position of the list and -2 being one position to the left of that.
Again, a little easier understand with 'a' 'b' 'c' 'd'
vals = ['a','b','c']
print(vals)
vals.insert(0,'d') # insert 'd' at positon zero
print(vals)
print(vals[1]) # display position 1
del vals[1] # delete position 1
print(vals)
A list object is indexed from 0 (zero) to the length of said object.
Maybe this will help:
position: | 0 | 1 | 2 | 3 | 4 |
data: | a | b | c | d | e |
- position: | -5 | -4 | -3 | -2 | -1 |
range(n) is a function that return an iterable
starting in 0 and ends in n-1
First step len(my_list) returns 3
Then range(3) returns the iterable (0,1,2)
In each iteration you are altering my_list
For brevity, I have edited the quote to show you
an example.
Run the code and see what is happening.
it’s better let’s discuss this one by one of these two examples here:-
for first example here:-
in my first example here i am unable to understand why does print(v) returns values like this
0
1
2
but not like this 0 1 2
secondly for below peice of code:-
my_list.insert(1, my_list[v])
print(my_list)
as per my understanding above code should put my_list[v] at first index ( which i think should be number 2 as per my example here) but still not clear how below output is getting generated here:-
0
1
2
[1, 1, 1, 1, 2, 3]
What I’ve already posted, in this thread, answers this question, so I’m not too sure if it’s simply not clear to you or if you’re ignoring what I’ve posted.
my_list[-1] will return -2 and my_list[-2] will return 1, which is what the print() function is displaying: -1 being the last position of the list and -2 being one position to the left of that.