+ 1
Question on index () method
L = [1,2,6,88,25,662,256] 1.L.index (88,0,4) will return 3 2. L.index (88, -1) will throw ValueError: 88 is not in list 3. L.index (256,-1) will return 6 4. L.index (25, -1,-4) will return ValueError 5. L.index (25,-4,-1) will return 4 Why did 2 throw an error and not 3? Why did 4 throw an error and not 5?
3 odpowiedzi
+ 6
... then the end index, so [-1:-4] would be invalid, returning an empty list. Because of this, 25 is not within that empty list, therefore raising a ValueError
5) Because -4 is less than -1, the list splice L[-4:-1] would be valid, and would return [88, 25, 662, 256]. 25 is found within the sublist, and so the function returns its index in the full list
+ 5
The index function takes 3 parameters - the value to search for, start index, and end index. If the value you're looking for is within the list, then it will return its index. Including the start index and end index will create a sublist based on the start and end index, and search for the value within that sublist.
Going through each use of the function:
1) The value is searched within the sublist L[0:4], which is equivalent to [1,2,6,88]. Because 88 is found, it will return its index of 3
2) 88 is searched for within the sublist L[-1], which is just [256]. Because 88 is not in it, it will raise a ValueError
3) 256 is searched within the sublist L[-1], or [256], and because it is found it returns its value within the entire list (being 6)
4) When it comes to Python, negative indices are the same as just starting to count from the end of a list, so -1 would be the last element, -2 would be second last, etc. Because of this, you cannot have a list splice where the starting value is greater (continued)
+ 1
Thanks!! I get it now :)