0
Why python language is had a negtive index????
4 Antworten
+ 3
If you have a list in python, the first element has the index [0], the second element has the index[1] etc.
Negative indices start counting from the last element. [-1] is the last element, [-2] is the second last element etc.
So in a list l = ['a', 'b', 'c'] you can address the element 'c' both as l[2] (because it is the third element of the list) or as l[-1] (because it is also the last element of the list).
+ 2
If you mean something like this:
>> a = [1,2,3,4,5]
>> a[-1]
5
It's used to refer to an iterator from its last element.
In our example,
>> a[-2]
4
If you desire a whole range, you can use [:] aside of the index. Lets say from 2nd element until the end of the array
>>a[1:]
[2,3,4,5]
Or lets say you want the last 2 items of the array:
>> a[-2:]
[4,5]
Or lets say you want from the beggining until the last-second element of the array:
>> a[:-1]
[1,2,3,4]
+ 1
A negative index means that it counts backwards from the end (of a list for example).
So, my_list[-1] is the last item in the list, my_list[-2] is the second last, and so on...
0
That's easier :
for example, you have a file name: file="D:/Python/p1.py" and you want the extension of the file...
So, you write :
extension=file.split("/")[-1].split(".")[-1]